I am refering to code from Case insensitive string replacement in JavaScript?:
RegExp.escape = function(str)
{
var specials = new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"); // .*+?|()[]{}\
return str.replace(specials, "\\$&");
}
What does \\$& mean?
I think \\ escapes the \ character. Then $&, I thought it should be $1 to match the 1st match? tho $1 does not work right
$&represents the entire (sub)string matched by the regex, regardless of capture groups. The replacement result you get is each match in your string being escaped by a literal backslash (represented by\\). Since the regex used here consists only of a character class, “each match” refers to each metacharacter listed in the character class that is matched.For example, the regex string
[abc]will be replaced with\[abc\]:[is matched as it occurs in the character class. Represented by$&, replaced with\[a,bandcare not metacharacters in the character class, so they’re ignored]is matched as it occurs in the character class. Represented by$&, replaced with\]