admin管理员组

文章数量:1221774

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?

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?

Share Improve this question edited Mar 2, 2010 at 18:49 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Mar 2, 2010 at 17:13 user34537user34537 2
  • 2 The real question is why they're using a character class to match a single [ – friedo Commented Mar 2, 2010 at 17:20
  • @friedo I guess they don't know what [...] is character class – Ivan Nevostruev Commented Mar 2, 2010 at 17:23
Add a comment  | 

4 Answers 4

Reset to default 11

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

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 [].

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 \].

本文标签: regexWhat doesdo in JavaScriptStack Overflow