15

I want to replace backslash => '\' with secure \ replacement.

But my code replacing all '#' fails when applied for replacing '\':

el = el.replace(/\#/g, '#'); // replaces all '#' //that's cool
el = el.replace(/\\/g, '\'); // replaces all '\' //that's failing

Why?

Alcides Queiroz
  • 9,156
  • 3
  • 27
  • 42
Szymon Toda
  • 4,195
  • 11
  • 40
  • 61

2 Answers2

18

open console and type

'\'.replace(/\\/g, '\'); 

fails because the slash in the string isn't really in the string, it's escaping '

'\\'.replace(/\\/g, '\');

works because it takes one slash and finds it.

your regex works.

dansch
  • 5,648
  • 3
  • 40
  • 58
  • 1
    so how do you handle "domain\user" then? you got to first replace single backslash to double and then use .replace(/\\/g, '\'); ? – HaBo Apr 07 '16 at 09:23
  • `/\\/g` looks for a single backslash. At no point are we replacing a single with a double. The first backslash escapes the second one, so this regex looks for a single backslash, globally. to handle "domain\user", `/\\/g` should work fine. – dansch Apr 14 '16 at 14:00
2

You can use String.raw to add slashes conveniently into your string literals. E.g. String.raw`\a\bcd\e`.replace(/\\/g, '\');

Alan Pierce
  • 3,913
  • 2
  • 21
  • 19
Tamas Rev
  • 6,728
  • 5
  • 31
  • 49