1

I try to replace all occurences of \ in a string, but I can't find the way, even after searching on the web and here.

This is what I tried :

$ node
> var x = 'foo\bar\base'
> x.replace(/\\/g, '/');
'foo\bar\base'

I expect foo/bar/base but the string is unchanged.

Same thing with split() :

> x.split('\\')
[ 'foo\bar\base' ]

Context: this is from the DOM, I get this string with

var node = document.querySelector(sel);
node.innerText.replace(/\\/g, '/');

Edit there's a confusion between my try in and what I can have in real browser, check @Jeffrey Westerkamp comment in this answer

MevatlaveKraspek
  • 2,246
  • 3
  • 20
  • 23
  • 3
    Replace returns a new string – Get Off My Lawn Jun 04 '18 at 18:09
  • Technically speaking, there are no backslahes in your string. When you input a backslash character in a string literal, it's actually an escape character for what comes next. So, `\b` is the character. (I don't know off the top of my head *what* character, but it's something.) If you want backslashes in your string literal, use `\\`. That effectively cancels the escape and becomes a single backslash in the string. – Brad Jun 04 '18 at 18:13

2 Answers2

3

escape the backslashes in your original string:

var x = 'foo\\bar\\base'

explanation: the \ is the default escape character - in your original string, each \b pair is a backspace - to include a backslash in a string literal, you need to escape it, i.e. \\

ic3b3rg
  • 14,629
  • 4
  • 30
  • 53
0

I've found a solution :

node.innerText.split('\\').join("/")
MevatlaveKraspek
  • 2,246
  • 3
  • 20
  • 23
  • Still, this is weird. writing `var x = "foo\bar\baz"` in node `v6.11` results in `"foo\bar\baz"`, but doing the same thing in the chrome console results in `"fooaraz"`. (?) – JJWesterkamp Jun 04 '18 at 18:27
  • 1
    Update: I found [this SO answer](https://stackoverflow.com/a/43610251/6361314) that explains the concept that's likely to be at work here. – JJWesterkamp Jun 04 '18 at 18:36