鉴于此功能:
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).
就个人而言,我不是因为这个原因而建立regexp使用字符串的忠实粉丝。逃脱的水平可能导致你喝酒。我确信其他人会有不同的感觉,并且喜欢在写正则表达时喝酒。
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替换/正则表达式
发布评论