在javascript中替换所有支撑的字符串

时间:2015-06-09 01:42:13

标签: javascript

我想这样做:

i went to the [open shops], but the [open shops] were closed

看起来像这样:

i went to the markets, but the markets were closed

使用javascript替换

我对正则表达式不是很好,方括号需要分隔确定

3 个答案:

答案 0 :(得分:3)

试试这个:

"i went to the [open shops], but the [open shops] were closed".replace(/\[open shops\]/g, 'markets');

棘手的部分是需要转义括号并添加全局匹配来替换每个匹配的实例。有关详细信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

答案 1 :(得分:1)

您需要做的就是在[和]之前将\视为普通角色。这样你的正则表达式就会变成\[openshops\]

如果您有多个需要替换的内容(例如[shops][state]),您可以执行以下操作,动态创建正则表达式。通过这种方式,您无需为每件事物进行硬编码。

var str = "I went to the [shops], but the [shops] were [state]. I hate it when the [shops] are [state].";
    var things = {
        shops: "markets",
        state: "closed"
    };
    for (thing in things) {
        var re = new RegExp("\\["+thing+"\\]", "g");
        str = str.replace(re, things[thing]);
    }
console.log(str);

请注意,在执行此操作时,您需要使用两个反斜杠而不是一个反斜杠。

答案 2 :(得分:0)

如果您不想使用正则表达式。你可以使用类似的东西。

    var a = "i went to the [open shops], but the [open shops] were closed";
    var replacement = "KAPOW!";

    while(a.contains("[") && a.contains("]"))
    {
        var left = a.indexOf("[");
        var right = a.indexOf("]");

        a = a.substring(0,left) + replacement + a.substring(right+ 1);
    }

    console.log(a);