0

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/

yuli chika
  • 9,053
  • 20
  • 75
  • 122

4 Answers4

3

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.

Community
  • 1
  • 1
Philipp Gayret
  • 4,870
  • 1
  • 28
  • 34
1

Replace all numbers between [ and ] to new.

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

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

Demo

rgtk
  • 3,240
  • 1
  • 30
  • 36
0

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/

aorcsik
  • 15,271
  • 5
  • 39
  • 49
0

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
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375