简体   繁体   中英

javascript replace all string and variable with global

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);

http://jsfiddle.net/P8HSA/

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 .

Replace all numbers between [ and ] to new .

var a = 'some thing [0]  [1]  [0]  [1] ';

a = a.replace(/\[\d\]/g, 'new');

Demo

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM