Skip to main content
Known Participant
October 1, 2008
Answered

Eliminate Spaces from Character String

  • October 1, 2008
  • 3 replies
  • 998 views
Hi,
Does anyone have a simple routine/function to eliminate all but 1 space between "words" (consectutive charactives with no spaces).

For example, I'd like to convert the string (I've used '.' as a "space":

"This...has....too..many...spaces" to
"This.has.too.many.spaces".

I need this to compare inputed character strings where a user may have hit the space bar an extra time or 2.

Thanks in advance.
    This topic has been closed for replies.
    Correct answer Newsgroup_User
    hefterr wrote:
    > Thanks Dan. This looks good.
    > Can I use ...
    > <cfloop condition="mystring contains " ""> Not sure about the quotes for 2
    > spaces

    You need to alternate quotes when nesting them like that... Take your pick.

    <cfloop condition="myString Contains ' '">
    OR
    <cfloop condition='myString Contains " "'>

    3 replies

    Inspiring
    October 1, 2008
    Dear God please don't use a loop to solve this. Just use RegEx, reReplace(yourString, "\s+", " ", "ALL").

    So much easier and cleaner!
    hefterrAuthor
    Known Participant
    October 1, 2008
    Hi Stressed,
    I tried both and actually went your way using :

    <cfset s = rereplace(s, "[[:space:]]{2,}", " ","all")>
    Is this the same regex as yours - I'm not well versed in regex's?
    Inspiring
    October 1, 2008
    That is cool, your regex is essentially the same! Regex is brilliant, I hope you enjoy getting versed! :D
    Inspiring
    October 1, 2008
    while(yourstring contains " ")
    yourstring = replace(yourstring, " ", " ", "all");
    hefterrAuthor
    Known Participant
    October 1, 2008
    Thanks Dan. This looks good.
    Can I use ...
    <cfloop condition="mystring contains " ""> Not sure about the quotes for 2 spaces
    <cfset mystring = replace(mystring, " ", " ", all> replace 2 spaces with 1 space
    </cfloop>

    tclaremont
    Inspiring
    October 1, 2008
    Look up the REREPLACE function. It sounds like what you want to do is replace all instances of a double space with a single space.

    You also might consider using the TRIM function on your inputted fields to elimiate leading and trailing spaces.