What does /[\[]/ do in JavaScript?

javascript, regex

Solution

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")

Problem

I am having trouble googling this. In some code I see ``` name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); ``` `/[\[]/` looks to be 1 parameter. What do the symbols do? It looks like it's replacing [] with `\[\]` but what specifically does `/[\[]/` do?

Original source