I think the confusion is coming from how a string is displayed in the browser console. (I just checked chrome)
let myString = "This is my \string";
Here myString is actually doesn't include any backslash char. It includes \s
sequence which resolves to s
.
So If you display your string in the console:
> myString =>
"This is my string"
> console.log(myString)
This is my string
The following string though has only 1 backslash in it:
let myString = "This is my \\string";
//string representation includes the escape char as well. So we see double backslashes.
> myString =>
"This is my \\string"
//When you print it, the escape char is not there.
> console.log(myString)
This is my \string
So finally if you want to replace backslash char with 2 backslashes you can do this:
let myNewStringWith2Backslashes= myString.replace("\\","\\\\")