Reputation: 17906
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(")","]")
Upvotes: 10
Views: 63582
Reputation: 7985
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, "")
Upvotes: 19
Reputation: 15176
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]
Upvotes: 3
Reputation: 150030
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) + "]";
Upvotes: 34
Reputation: 7068
This Javascript should do the job as well as the answer by 'nnnnnn' above
stringObject = stringObject.replace('(', '[').replace(')', ']')
Upvotes: 4
Reputation: 5458
var s ="(53.5595313, 10.009969899999987)";
s.replace(/\((.*)\)/, "[$1]")
Upvotes: 7