How to remove square brackets in string using regex?

Viewed 130738

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

6 Answers

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, "");
Related