【问题标题】:Replace all braced strings in javascript替换javascript中的所有大括号字符串
【发布时间】:2025-06-15 12:50:01
【问题描述】:

我想做这个:

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

看起来像这样:

i went to the markets, but the markets were closed

用javascript替换

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

【问题讨论】:

  • 也许一个正则表达式教程或在线正则表达式测试器会是更好的第一步?
  • @DaveNewton:甚至是谷歌*.com/questions/4292468/…

标签: javascript


【解决方案1】:

试试这个:

"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

【讨论】:

  • 谢谢 - 我很接近 - 我在整个正则表达式周围加上引号,因此 .replace("/[open stores]/g","sd")。我认为这个空间也可能需要逃逸。但显然不是。再次感谢。
  • @case1352 在正则表达式问题中,包含您正在使用的正则表达式可能是有意义的。
【解决方案2】:

您需要做的就是将 \ 放在 [ 和 ] 之前,以将其视为常规字符。这样你的正则表达式就会变成\[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);

注意,这样做时你需要使用两个反斜杠而不是一个。

【讨论】:

    【解决方案3】:

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

        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);
    

    【讨论】:

    • 在这种情况下,Regex 似乎是一个更好的工具。
    • 阅读一个简单的正则表达式比阅读几行代码要容易得多——如果不是这样,那就是正则表达式知识的不足,而 IMO 必须具备这一点。
    • 我同意 regex 是更好的选择,但对于初学者来说,就像刚刚做 hello world tuts 的技能水平一样,我认为 regex 是复杂性的跳跃。但这可能只是我自己,我只是提供了一个我觉得更容易阅读的替代方案。我可能会首先以不同的方式构建字符串:D.