有没有一种简单的方法来制作这个字符串:
(53.5595313, 10.009969899999987)
到这个字符串
[53.5595313, 10.009969899999987]
使用 JavaScript 还是 jQuery?
我尝试了多个替换,这对我来说似乎不太优雅
str = str.replace("(","[").replace(")","]")
有没有一种简单的方法来制作这个字符串:
(53.5595313, 10.009969899999987)
到这个字符串
[53.5595313, 10.009969899999987]
使用 JavaScript 还是 jQuery?
我尝试了多个替换,这对我来说似乎不太优雅
str = str.replace("(","[").replace(")","]")
好吧,既然您要求使用正则表达式:
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) + "]";
对于它的价值,替换 ( 和 ) 使用:
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, "")
var s ="(53.5595313, 10.009969899999987)";
s.replace(/\((.*)\)/, "[$1]")
这个 Javascript 应该可以完成这项工作以及上面 'nnnnnn' 的答案
stringObject = stringObject.replace('(', '[').replace(')', ']')
如果您不仅需要一对括号,还需要多个括号替换,则可以使用此正则表达式:
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]