Reputation: 891
['abc','xyz']
– this string I want turn into abc,xyz
using regex in javascript. I want to replace both open close square bracket & single quote with empty string ie ""
.
Upvotes: 56
Views: 162009
Reputation: 20088
we can easily replace [ and ] using replace() method in javascript in the following way.
console.log("['abc','xyz']".replace('[','').replace(']', ''));
Upvotes: 0
Reputation: 345
Just here to propose an alternative that I find more readable.
/\[|\]/g
JavaScript implementation:
let reg = /\[|\]/g
str.replace(reg,'')
As other people have shown, all you have to do is list the [
and ]
characters, but because they are special characters you have to escape them with \
.
I personally find the character group definition using []
to be confusing because it uses the same special character you're trying to replace.
Therefore using the |
(OR) operator you can more easily distinguish the special characters in the regex from the literal characters being replaced.
Upvotes: 0
Reputation: 838156
Use this regular expression to match square brackets or single quotes:
/[\[\]']+/g
Replace with the empty string.
console.log("['abc','xyz']".replace(/[\[\]']+/g,''));
Upvotes: 104
Reputation: 323
here you go
var str = "['abc',['def','ghi'],'jkl']";
//'[\'abc\',[\'def\',\'ghi\'],\'jkl\']'
str.replace(/[\[\]']/g,'' );
//'abc,def,ghi,jkl'
Upvotes: 14
Reputation: 993055
You probably don't even need string substitution for that. If your original string is JSON, try:
js> a="['abc','xyz']"
['abc','xyz']
js> eval(a).join(",")
abc,xyz
Be careful with eval
, of course.
Upvotes: 4