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,456
  • 3
  • 28
  • 43
Szymon Toda
  • 4,454
  • 11
  • 43
  • 62

2 Answers2

19

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
  • 6,059
  • 4
  • 43
  • 59
  • 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
3

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

Alan Pierce
  • 4,083
  • 2
  • 22
  • 21
Tamas Rev
  • 7,008
  • 5
  • 32
  • 49