JavaScript替换/正则表达式

编程入门 行业动态 更新时间:2024-10-12 18:22:18
本文介绍了JavaScript替换/正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

鉴于此功能:

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替换/正则表达式

本文发布于:2023-06-11 03:32:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/625759.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正则表达式   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!