What does % do in JavaScript?

The syntax /…/ is the literal regular expression syntax. And the regular expression [\[] describes a character class ([…]) that’s only character the [ is). So /[\[]/ is a regular expression that describes a single [.

But since the global flag is not set (so only the first match will be replaced), the whole thing could be replaced with this (probably easier to read):

name.replace("[", "\\[").replace("]","\\]")

But if all matches should be replaced, I would probably use this:

name.replace(/([[\]])/g, "\\$1")

The [] is in regex itself used to denote a collection of to-be-matched characters. If you want to represent the actual [ or ] in regex, then you need to escape it by \, hence the [\[] and [\]]. The leading and trailing / are just part of the standard JS syntax to to denote a regex pattern.

After all, it replaces [ by \[ and then replaces ] by \].


It's a regular expression that matches the left square bracket character.

It's a weird way to do it; overall it looks like the code is trying to put backslashes before square brackets in a string, which you could also do like this:

var s2 = s1.replace(/\[/g, '\\[').replace(/]/g, '\\]');

I think.


/[[]/ defined a character range which includes only the ']' character (escaped), you are correct that is replaced [] with [].