Reputation: 180
I know this line escapes a javascript string by adding \ before special characters. But can anyone explain how it does that? And also. Can it cause any problems in further string manipulations.
str = str.replace(/[-\\/\\^$*+?.()|[\]{}]/g, '\\$&');
Upvotes: 0
Views: 70
Reputation: 4239
The regular expression replaces anything it matches with backslash and the matched substring. It matches any single characters of the set between [
and ]
. That is:
-
simple dash\\
single backslash (preceded by another backslash, because it server as escape character)/
slash\\
single backslash again (it is obsolete here)^
, $
, *
, +
, ?
, .
, (
, )
, |
, [
single characters\]
closing bracket is preceded by escape character, otherwise it would close set of characters to match{
, }
single charactersThe replacement string \\$&
simply says:
\\
add single backslash$&
add the whole substring matched by the expressionUpvotes: 1