jQuery 简单的正则表达式替换括号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15585569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple regex replace brackets
提问by john Smith
is there an easy way to make this string :
有没有一种简单的方法来制作这个字符串:
(53.5595313, 10.009969899999987)
to this String
到这个字符串
[53.5595313, 10.009969899999987]
with javascript or jquery ?
使用 javascript 或 jquery 吗?
回答by nnnnnn
Well, since you asked for regex:
好吧,既然你要求正则表达式:
var input = "(53.5595313, 10.009969899999987)";
var output = input.replace(/^\((.+)\)$/,"[]");
// OR to replace all parens, not just one at start and end:
var output = input.replace(/\(/g,"[").replace(/\)/g,"]");
...but that's kind of complicated. You could just use .slice()
:
……但这有点复杂。你可以使用.slice()
:
var output = "[" + input.slice(1,-1) + "]";
回答by Shuping
var s ="(53.5595313, 10.009969899999987)";
s.replace(/\((.*)\)/, "[]")
回答by Muhammad Omar ElShourbagy
This Javascript should do the job as well as the answer by 'nnnnnn' above
这个Javascript应该完成这项工作以及上面'nnnnnn'的答案
stringObject = stringObject.replace('(', '[').replace(')', ']')
stringObject = stringObject.replace('(', '[').replace(')', ']')
回答by bob
For what it's worth, to replace both { and } use:
对于它的价值,替换 { 和 } 使用:
str = "{boob}";
str = str.replace(/[\{\}]/g, ""); // yields "boob"
回答by Kai Noack
If you need not only one bracket pair but several bracket replacements, you can use this regex:
如果您不仅需要一对括号,而且需要替换多个括号,您可以使用以下正则表达式:
var input = "(53.5, 10.009) more stuff then (12) then (abc, 234)";
var output = input.replace(/\((.+?)\)/g, "[]");
console.log(output);
[53.5, 10.009] more stuff then [12] then [abc, 234]
[53.5, 10.009] 更多的东西然后 [12] 然后 [abc, 234]