views:

192

answers:

2

I have the following jquery statement. I wish to remove the whitespace as shown below. So if I have a word like:

For example

  • #Operating/System I would like the end result to show me #Operating\/System. (ie with a escape sequence).


  • But if I have #Operating/System test then I want to show #Operating\/System + escape sequence for space. The .replace(/ /,'') part is incorrect but .replace("/","\\/") works well as per my requirements.

Please help!

$("#word" + lbl.eq(i).text().replace("/","\\/").replace(/ /,'')).hide();
A: 

In your example:

$("#word" + lbl.eq(i).text().replace("/","\\/").replace(/ /,'')).hide();

The / / in the second replace isn't in a string, but a regex literal. As with your previous question, you need to use g in order to replace all occurrences of a space character (though I'm not sure if that's the desired behaviour).

$("#word" + lbl.eq(i).text().replace("/","\\/").replace(/ /g,"+")).hide();
Matt Ball
Whoops, you're right. I'm trying to keep regex syntax for too many languages in my head at once.
Matt Ball
+1  A: 
$( "#word" + lbl.eq(i).text().replace(/([ /])/g, '\\$1') ).hide();

This matches all spaces and slashes in a string (and saves the respective char in group $1):

/([ /])/g

replacement with

'\\$1'

means a backslash plus the original char in group $1.

"#Operating/System test".replace(/([ /])/g, '\\$1');
-->
"#Operating\/System\ test"

Side advantage - there is only a singe call to replace().

EDIT: As requested by the OP, a short explanation of the regular expression /([ /])/g. It breaks down as follows:

/           # start of regex literal
  (         # start of match group $1 
    [ /]    # a character class (spaces and slashes)
  )         # end of group $1
/g          # end of regex literal + "global" modifier

When used with replace() as above, all spaces and slashes are replaced with themselves, preceded by a backslash.

Tomalak
Well this works fantastic so anything with spaces ex "Operating System" works fine but anything with SLASHES ex. "Operating/System" or "Operating/System test" is not working. Also, I would really really appreciate it if you can explain this replace(/([ /])/g, '\\$1') statement as i don't understand it. Thanks again.
SA
I've just tested it - for me it replaces slashes as well. How did you test?
Tomalak
There are no double quotes in my code, and it's not an accident. ;-) You should read a few lines on `replace()` in particular and regular expressions in general.
Tomalak
@Tomalak. Thank you for the explanation and you are right it works in a single replace for spaces and slashes. You have a mastery over this. Thank you, Thank you, thank you .... again and again. You saved my life today!!
SA