给定此函数:
function Repeater(template) {
var repeater = {
markup: template,
replace: function(pattern, value) {
this.markup = this.markup.replace(pattern, value);
}
};
return repeater;
};
如何让this.markup.replace()
全局替换?问题就在这里。如果我这样使用它:
alert(new Repeater("$TEST_ONE $TEST_ONE").replace("$TEST_ONE", "foobar").markup);
警报的值是"foobar $TEST_ONE“。
如果我将Repeater
更改为以下内容,则Chrome中没有任何内容被替换:
function Repeater(template) {
var repeater = {
markup: template,
replace: function(pattern, value) {
this.markup = this.markup.replace(new RegExp(pattern, "gm"), value);
}
};
return repeater;
};
...and警报是$TEST_ONE $TEST_ONE
。
发布于 2009-07-22 01:02:49
您需要对任何RegExp字符进行双重转义(一次用于字符串中的斜杠,一次用于正则表达式):
"$TESTONE $TESTONE".replace( new RegExp("\\$TESTONE","gm"),"foo")
否则,它会查找行尾和'TESTONE‘(它永远找不到)。
就我个人而言,出于这个原因,我不喜欢使用字符串构建regexp。所需的逃脱程度可能会导致你饮酒。但我相信其他人会有不同的感受,他们喜欢在编写正则表达式时饮酒。
https://stackoverflow.com/questions/1162529
复制相似问题