0

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, '\\$&');
  • Why use RegExp? There are easier and more reliable ways to escape a string. Like this for example: `JSON.stringify('This is " a \\ test')` – David784 Jan 18 '19 at 14:46
  • "*Can it cause any problems in further string manipulations.*" - only you know what you are trying to do with the string and whether the escaping would cause problems for that. We don't know the purpose of your code, we cannot judge it. – Bergi Jan 18 '19 at 14:54
  • This looks very much like [the escaping you'd do to use the string in a dynamically built regular expression](https://stackoverflow.com/q/3561493/1048572). Is that what you actually need it for? If not, the don't use this code - yes it will cause problems. – Bergi Jan 18 '19 at 14:56
  • yes this is exactly what i need it for. – Muhammad Usama Jan 18 '19 at 15:01
  • Do you guys recommend using this approach? – Muhammad Usama Jan 18 '19 at 15:04
  • i have to find a document from mongoDB which name is exactly the same as user entered also ignoring the case. – Muhammad Usama Jan 18 '19 at 15:07

1 Answers1

1

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 characters

The replacement string \\$& simply says:

  • \\ add single backslash
  • $& add the whole substring matched by the expression
Roman Hocke
  • 4,137
  • 1
  • 20
  • 34