How can I put [] (square brackets) in RegExp javascript?

It should be:

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

You don’t need double backslashes (\) because it’s not a string but a regex statement, if you build the regex from a string you do need the double backslashes ;).

It was also literally interpreting the 1 (which wasn’t matching). Using .* says any value between the square brackets.

The new RegExp string build version would be:

str=str.replace(new RegExp("\\[.*?\\]","g"),"");

UPDATE: To remove square brackets only:

str = str.replace(/\[(.*?)\]/g,"$1");

Your above code isn’t working, because it’s trying to match “[]” (sequentially without anything allowed between). We can get around this by non-greedy group-matching ((.*?)) what’s between the square brackets, and using a backreference ($1) for the replacement.

UPDATE 2: To remove multiple square brackets

str = str.replace(/\[+(.*?)\]+/g,"$1");
// bla [bla] [[blaa]] -> bla bla blaa
// bla [bla] [[[blaa] -> bla bla blaa

Note this doesn’t match open/close quantities, simply removes all sequential opens and closes. Also if the sequential brackets have separators (spaces etc) it won’t match.

Leave a Comment