开发者

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

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开发者_StackOverflow中文版? It looks like it's replacing [] with \[\] but what specifically does /[\[]/ do?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜