fish man
fish man

Reputation: 101

What does this regular expression: /[\[]/?

I am struggling to understand what this means: /[\[]/ Why are there two replace statements?

name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");

Upvotes: 3

Views: 95

Answers (4)

Denys Séguret
Denys Séguret

Reputation: 382132

/[\[]/ is a regular expression literal.

In the first replacement, you're replacing a [ by \[ and the symetric in the second one.

It looks weird because of many (mostly useless) escapements : [ is escaped in the regex and \ and [ are escaped in the string literal.

The first regex can be analyzed like this :

  • / : regex opening
  • [ : character set opening
  • \[ : the [ character (with an escaping that is useless as it's in a set)
  • ] : character set closing
  • / : regex closing

Those regexes look too verbose to me : you don't need a character set if you have just one character in that set. And you don't need to escape the [ in the string literal.

You could have done

 name = name.replace(/\[/, "\\[").replace(/\]/, "\\]");

For example

 'a [ b c ] d [ e ]'.replace(/\[/, "\\[").replace(/\]/, "\\]")

gives

 "a \[ b c \] d [ e ]"

Note that as there is no g modifier, you're only doing one replacement in each call to replace, which probably isn't the goal, so you might want

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

Upvotes: 8

jtomaszk
jtomaszk

Reputation: 11171

Maybe you will see how it works on example

var name = "[[[[[]]]]]]]";
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
console.log(name);

as result you will have

\[[[[[\]]]]]]] 

This regular expression replace first occurrence of [ to \[ and first occurrence ] to \]

Upvotes: 0

PaulG
PaulG

Reputation: 7102

This really isn't specific to Javascript, regular expressions are used in most programming languages with slight variations. Look into regular expressions, very useful once you know it!

Upvotes: 0

Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22094

That is using regular expression. If you are not familiar with regular expression, you may want to study that first.

Upvotes: 0

Related Questions