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

Viewed 69361

I'm trying this:

str = "bla [bla]";
str = str.replace(/\\[\\]/g,"");
console.log(str);

And the replace doesn't work, what am I doing wrong?

UPDATE: I'm trying to remove any square brackets in the string, what's weird is that if I do

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

it works, but
replace(/\[\]/g, '');
doesn't.

8 Answers

Here's a trivial example but worked for me. You have to escape each sq bracket, then enclose those brackets within a bracket expression to capture all instances.

const stringWithBrackets = '[]]][[]]testing][[]][';
const stringWithReplacedBrackets = stringWithBrackets.replace(/[\[\]]/g, '');
console.log(stringWithReplacedBrackets);

I stumbled on this question while dealing with square bracket escaping within a character class that was designed for use with password validation requiring the presence of special characters.

Note the double escaping:

var regex = new RegExp('[\\]]');

As @rudu mentions, this expression is within a string so it must be double escaped. Note that the quoting type (single/double) is not relevant here.

Here is an example of using square brackets in a character class that tests for all the special characters found on my keyboard:

var regex = new RegExp('[-,_,\',",;,:,!,@,#,$,%,^,&,*,(,),[,\\],\?,{,},|,+,=,<,>,~,`,\\\\,\,,\/,.]', 'g')

How about the following?

str = "bla [bla]";

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

You create a character set with just the two characters you are interested in and do a global replace.

Nobody quite made it simple and correct:

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

Note the use of a character class, with no escape for the open bracket, and a single backslash escape for the close bracket.

Related