简体   繁体   English

javascript用global替换所有字符串和变量

[英]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 ? 为什么我不能将全部[0][1]替换为new Here is some simple example, in the real situation, [0][1][2]... with more condition. 这是一个简单的示例,在实际情况下,[0] [1] [2] ...具有更多条件。 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/ http://jsfiddle.net/P8HSA/

Because 因为

#1 #1

Your regular expression is now ( example with 0 [0] ); 您的正则表达式现在是(例如0 [0] ); This will match <space>0<space/> You're probably looking for " \\\\["+i+"\\\\] " as brackets are a special character, 这将匹配<space>0<space/>您可能正在寻找" \\\\["+i+"\\\\] "因为方括号是特殊字符,

#2 #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. 哪个输出( some thingnewnewnewnewnew some thingnewnewnewnewnew ,我希望这是预期的结果。

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 . 将[和]之间的所有数字替换为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. for循环在这里是多余的,因为正则表达式可以立即使用。 Also I recommend the literal syntax /.../ . 我也建议使用文字语法/.../

Working fiddle: http://jsfiddle.net/P8HSA/6/ 工作提琴: http : //jsfiddle.net/P8HSA/6/

Strings are immutable and replace does return the new, modified value. 字符串是不可变的,并且replace会返回修改后的新值。 You will have to reassign it to your a variable yourself (See Replace method doesn't work ): 你将不得不重新分配给你的a变量自己(见更换方法不起作用 ):

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: 现在,您可以使用实际的字符类来一次匹配从0到2的所有数字:

var a = 'some thing [0]  [1]  [0]  [1] ';
alert(a.replace(/\[[0-3]\]/g, ' new')); // regex literal to simplify syntax

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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