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/

0

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Replace all numbers between [ and ] to new.

var a = 'some thing [0] [1] [0] [1] '; a = a.replace(/\[\d\]/g, 'new'); 

Demo

Comments

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/

Comments

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.