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();
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();
Share
Improve this question
edited Nov 9, 2009 at 22:31
Matt Ball
360k102 gold badges653 silver badges720 bronze badges
asked Nov 9, 2009 at 22:08
user176820user176820
6
- 1 Glad you got your clarification correct in your head, but you should have just updated your other question: stackoverflow./questions/1703529/… – Crescent Fresh Commented Nov 9, 2009 at 22:15
- Well. I will mark the answer there for future reference. But this is a new question. Thanks for helping me! – user176820 Commented Nov 9, 2009 at 22:16
- I would (tentatively) say that you are trying to do the wrong thing (or the right thing in the wrong way, which is just as bad). Why do you want to escape certain characters in a string? – Tomalak Commented Nov 9, 2009 at 22:21
- 1 I think he wants to dynamically use text on a page as a selector for jQuery. I agree that there are several potential problems with this. – Josh Stodola Commented Nov 9, 2009 at 22:23
- Well I am dynamically reading an id (asp) which contains slashes and spaces and then hiding those particular selectors with those values. – user176820 Commented Nov 9, 2009 at 22:24
1 Answer
Reset to default 2$( "#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.