繁体   English   中英

简单的正则表达式替换括号

[英]Simple regex replace brackets

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

(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) + "]";
var s ="(53.5595313, 10.009969899999987)";
s.replace(/\((.*)\)/, "[$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)

这个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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM