简体   繁体   中英

How to remove square brackets in string using regex?

['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 "" .

Use this regular expression to match square brackets or single quotes:

/[\[\]']+/g

Replace with the empty string.

 console.log("['abc','xyz']".replace(/[\\[\\]']+/g,''));

str.replace(/[[\\]]/g,'')

here you go

var str = "['abc',['def','ghi'],'jkl']";
//'[\'abc\',[\'def\',\'ghi\'],\'jkl\']'
str.replace(/[\[\]']/g,'' );
//'abc,def,ghi,jkl'

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.

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.

This should work for you.

str.replace(/[[\]]/g, "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM