JavaScript 替换/正则表达式

编程入门 行业动态 更新时间:2024-10-10 23:26:44
本文介绍了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).

就我个人而言,由于这个原因,我不太喜欢使用字符串构建正则表达式.所需的逃避程度可能会导致您喝酒.我敢肯定,其他人在编写正则表达式时会有不同的感受,并且喜欢喝酒.

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

发布评论

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

>www.elefans.com

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