Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

I tried with multiple replace which seems not so elegant to me

 str = str.replace("(","[").replace(")","]")
like image 682
john Smith Avatar asked Mar 23 '13 10:03

john Smith


People also ask

What is $1 in RegEx replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

Can RegEx replace characters?

RegEx makes replace ing strings in JavaScript more effective, powerful, and fun. You're not only restricted to exact characters but patterns and multiple replacements at once.

How do you change square brackets in Java?

String str = "[Chrissman-@1]"; str = replaceAll("\\[\\]", ""); String[] temp = str. split("-@"); System. out. println("Nickname: " + temp[0] + " | Power: " + temp[1]);


2 Answers

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():

var output = "[" + input.slice(1,-1) + "]";
like image 94
nnnnnn Avatar answered Sep 21 '22 23:09

nnnnnn


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)

Edit

Actually, the two escape characters are redundant and eslint will warn you with:

Unnecessary escape character: ) no-useless-escape

The correct form is:

str.replace(/[()]/g, "")
like image 32
bob Avatar answered Sep 17 '22 23:09

bob