Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

javascript - JavaScript替换/正则表达式(JavaScript replace/regex)

Given this function:(鉴于此功能:)

function Repeater(template) { var repeater = { markup: template, replace: function(pattern, value) { this.markup = this.markup.replace(pattern, value); } }; return repeater; }; How do I make this.markup.replace() replace globally?(如何使this.markup.replace()全局替换?) Here's the problem.(这是问题所在。) If I use it like this:(如果我像这样使用它:) alert(new Repeater("$TEST_ONE $TEST_ONE").replace("$TEST_ONE", "foobar").markup); The alert's value is "foobar $TEST_ONE".(警报的值为“foobar $ TEST_ONE”。) If I change Repeater to the following, then nothing in replaced in Chrome:(如果我将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 the alert is $TEST_ONE $TEST_ONE .(...并且警报是$TEST_ONE $TEST_ONE 。)   ask by core translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to double escape any RegExp characters (once for the slash in the string and once for the regexp):(你需要双重转义任何RegExp字符(一次用于字符串中的斜杠,一次用于regexp):)

"$TESTONE $TESTONE".replace( new RegExp("\$TESTONE","gm"),"foo") Otherwise, it looks for the end of the line and 'TESTONE' (which it never finds).(否则,它会查找该行的结尾和'TESTONE'(它从未找到)。) Personally, I'm not a big fan of building regexp's using strings for this reason.(就个人而言,由于这个原因,我不是建立regexp使用字符串的忠实粉丝。) 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.(我确信其他人会有不同的感受,并且在写正则表达时喜欢喝酒。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...