View previous topic :: View next topic |
Author |
Message |
Trow Grandmaster Cheater
Reputation: 2
Joined: 17 Aug 2006 Posts: 957
|
Posted: Mon Feb 08, 2010 10:51 am Post subject: [JS] Variable-bound Case-insensitive global string replace? |
|
|
Hi,
Normally, if you want to perform a string replacement in javascript, you do:
Code: | str=str.replace("what","lol"); |
but this is both case-sensitive and happens only for the first occurance of the term.
To do a case-insensitive global string replacement, there is regex:
Code: | str=str.replace(/what/gi,"lol"); |
and it works well.
Problem is, what should you do if you want a variable to be used inside the regex expression? The following are examples of things that don't work.
Code: | str=str.replace(/variablename/gi,"lol");
str=str.replace("/variablename/gi","lol");
str=str.replace("/" + variablename + "/gi","lol"); |
_________________
Get kidnapped often. |
|
Back to top |
|
 |
shhac Expert Cheater
Reputation: 0
Joined: 30 Oct 2007 Posts: 108
|
Posted: Mon Feb 08, 2010 1:10 pm Post subject: |
|
|
You can create regular expressions from strings (though usually it is better to use the /reg/ notation so only use this if the expression must be generated via string), for example, Code: | re = new RegExp("foo"+variable+"bar","gi");
str = str.replace(re,"lol"); | Remember to escape backslashes because this method uses a string and not direct typing of a RegEx.
|
|
Back to top |
|
 |
Trow Grandmaster Cheater
Reputation: 2
Joined: 17 Aug 2006 Posts: 957
|
Posted: Mon Feb 08, 2010 5:19 pm Post subject: |
|
|
works like a charm. thanks!
_________________
Get kidnapped often. |
|
Back to top |
|
 |
|