给定这个函数:
function Repeater(template) { var repeater = { markup: template, replace: function(pattern, value) { this.markup = this.markup.replace(pattern, value); } }; return repeater; };如何让 this.markup.replace() 全局替换?这就是问题所在.如果我像这样使用它:
How do I make this.markup.replace() replace globally? Here's the problem. If I use it like this:
alert(new Repeater("$TEST_ONE $TEST_ONE").replace("$TEST_ONE", "foobar").markup);警报的值为foobar $TEST_ONE".
The alert's value is "foobar $TEST_ONE".
如果我将 Repeater 更改为以下内容,则 Chrome 中不会替换任何内容:
If I change Repeater to the following, then nothing in replaced in Chrome:
function Repeater(template) { var repeater = { markup: template, replace: function(pattern, value) { this.markup = this.markup.replace(new RegExp(pattern, "gm"), value); } }; return repeater; };...警报为 $TEST_ONE $TEST_ONE.
推荐答案您需要对任何 RegExp 字符进行双重转义(一次用于字符串中的斜杠,一次用于 regexp):
You need to double escape any RegExp characters (once for the slash in the string and once for the regexp):
"$TESTONE $TESTONE".replace( new RegExp("\$TESTONE","gm"),"foo")否则,它会查找行尾和TESTONE"(它从未找到).
Otherwise, it looks for the end of the line and 'TESTONE' (which it never finds).
就我个人而言,由于这个原因,我不太喜欢使用字符串构建正则表达式.所需的逃避程度可能会导致您喝酒.我敢肯定,其他人在编写正则表达式时会有不同的感受,并且喜欢喝酒.
Personally, I'm not a big fan of building regexp's using strings for this reason. The level of escaping that's needed could lead you to drink. I'm sure others feel differently though and like drinking when writing regexes.
更多推荐
JavaScript 替换/正则表达式
发布评论