简体   繁体   中英

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

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.

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.

You have to escape the bracket, like \\[ and \\] . Check out http://regexpal.com/ . It's pretty useful :)

To replace all brackets in a string, this should do the job:

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

I hope this helps.
Hristo

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.

Two backslashes produces a single backslash, so you're searching for "a backslash, followed by a character class consisting of a 1 or a right bracket , and then you're missing an closing bracket.

Try

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

What exactly are you trying to match?

If you don't escape the brackets, they are considered character classes. This:

/[1\\]/

Matches either a 1 or a backslash. You may want to escape them with one backslash only:

/\[1\]/

But this won't match either, as you don't have a [1] in your string.

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.

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