JavaScript 替换/正则表达式 [英] JavaScript replace/regex

查看:37
本文介绍了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 替换/正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆