Reputation: 9221
How to replace all sting+variable? Why i can not replace all [0]
and [1]
into new
? Here is some simple example, in the real situation, [0][1][2]... with more condition. Thanks.
var a='some thing [0] [1] [0] [1] ';
for(var i=0; i<3; i++){
a.replace(new RegExp(" ["+i+"] ", 'g'),' new');
}
alert(a);
Upvotes: 0
Views: 153
Reputation: 664217
Strings are immutable and replace
does return the new, modified value. You will have to reassign it to your a
variable yourself (See Replace method doesn't work):
a = a.replace(new RegExp(" ["+i+"] ", 'g'), ' new');
Still, that's not enough to make it work since []
denote a character class in a regex. To match them literally, you will have to escape them with a backslash (and that again in the string literal):
a = a.replace(new RegExp(" \\["+i+"\\] ", 'g'), ' new');
Now, you could use an actual character class to match all digits from 0 to 2 at once:
var a = 'some thing [0] [1] [0] [1] ';
alert(a.replace(/\[[0-3]\]/g, ' new')); // regex literal to simplify syntax
Upvotes: 0
Reputation: 5060
Because
#1
Your regular expression is now ( example with 0 [0]
); This will match <space>0<space/>
You're probably looking for " \\["+i+"\\] "
as brackets are a special character,
#2
You're not storing the result of the replace, you should do:
a = a.replace(new RegExp(" \\["+i+"\\] ", 'g'),'new');
Comebine that, and you get
var a='some thing [0] [1] [0] [1] ';
for(var i=0; i<3; i++){
a = a.replace(new RegExp(" \\["+i+"\\] ", 'g'),'new');
}
alert(a);
Which outputs (Fiddle) some thingnewnewnewnewnew
and I hope that is the expected result.
Last but not least this is an abuse of regular expressions, and you can easily have a one line solution.
Upvotes: 3
Reputation: 15552
I would do it like this:
var a='some thing [0] [1] [0] [1] ';
a = a.replace(/\[[0-2]\]/g,' new');
alert(a);
A for loop is overkill here, since regular expressions can do it out of the box. Also I recommend the literal syntax /.../
.
Working fiddle: http://jsfiddle.net/P8HSA/6/
Upvotes: 0