【问题标题】:Simple regex replace brackets简单的正则表达式替换括号
【发布时间】:2013-03-13 05:00:10
【问题描述】:

有没有简单的方法来制作这个字符串:

(53.5595313, 10.009969899999987)

到这个字符串

[53.5595313, 10.009969899999987]

使用 JavaScript 还是 jQuery?

我尝试了多个替换,这对我来说似乎不太优雅

 str = str.replace("(","[").replace(")","]")

【问题讨论】:

  • 有。不过,我不会将自己限制在一个正则表达式中。一个用于左括号,一个用于右括号。

标签: javascript jquery regex


【解决方案1】:

好吧,既然您要求使用正则表达式:

var input = "(53.5595313, 10.009969899999987)";
var output = input.replace(/^\((.+)\)$/,"[$1]");

// OR to replace all parens, not just one at start and end:
var output = input.replace(/\(/g,"[").replace(/\)/g,"]");

...但这有点复杂。你可以使用.slice():

var output = "[" + input.slice(1,-1) + "]";

【讨论】:

    【解决方案2】:

    为了它的价值,替换 ( 和 ) 使用:

    str = "(boob)";
    str = str.replace(/[\(\)]/g, ""); // yields "boob"
    

    正则表达式字符含义:

    [  = start a group of characters to look for
    \( = escape the opening parenthesis
    \) = escape the closing parenthesis
    ]  = close the group
    g  = global (replace all that are found)
    

    编辑

    其实这两个转义字符是多余的,eslint 会警告你:

    不必要的转义字符:) no-useless-escape

    正确的形式是:

    str.replace(/[()]/g, "")
    

    【讨论】:

      【解决方案3】:
      var s ="(53.5595313, 10.009969899999987)";
      s.replace(/\((.*)\)/, "[$1]")
      

      【讨论】:

        【解决方案4】:

        这个 Javascript 应该和上面 'nnnnnn' 的答案一样完成这项工作

        stringObject = stringObject.replace('(', '[').replace(')', ']')

        【讨论】:

        • +1。但请注意,replace 在传递字符串时只进行一次替换。
        • 我假设作为提议的问题他只有一次出现,当括号只出现一次时,'nnnnnn' 的第二个答案也将适用于这个概念。
        【解决方案5】:

        如果您不仅需要一对括号,还需要多个括号替换,您可以使用这个正则表达式:

        var input = "(53.5, 10.009) more stuff then (12) then (abc, 234)";
        var output = input.replace(/\((.+?)\)/g, "[$1]");
        console.log(output);
        

        [53.5, 10.009] 更多的东西然后 [12] 然后 [abc, 234]

        【讨论】:

        • 这是一个优雅的答案。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-07
        • 2018-12-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多