[英]Simple regex replace brackets
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?
I tried with multiple replace which seems not so elegant to me我尝试了多次替换,这对我来说似乎不太优雅
str = str.replace("(","[").replace(")","]")
Well, since you asked for regex:好吧,既然你要求正则表达式:
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,"]");
...but that's kind of complicated. ……但这有点复杂。 You could just use .slice()
:你可以只使用.slice()
:
var output = "[" + input.slice(1,-1) + "]";
var s ="(53.5595313, 10.009969899999987)";
s.replace(/\((.*)\)/, "[$1]")
For what it's worth, to replace both ( and ) use:对于它的价值,替换 ( 和 ) 使用:
str = "(boob)";
str = str.replace(/[\(\)]/g, ""); // yields "boob"
regex character meanings:正则表达式字符含义:
[ = 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(')', ']')
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, "[$1]");
console.log(output);
[53.5, 10.009] more stuff then [12] then [abc, 234] [53.5, 10.009] 更多的东西然后 [12] 然后 [abc, 234]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.