Javascript and backslashes replace

Frankie picture Frankie · Mar 19, 2010 · Viewed 95.5k times · Source

here is my string:

var str = "This is my \string";

This is my code:

var replaced = str.replace("/\\/", "\\\\");

I can't get my output to be:

"This is my \\string"

I have tried every combination I can think of for the regular expression and the replacement value.

Any help is appreciated!

Answer

thegajman picture thegajman · Mar 25, 2014

Got stumped by this for ages and all the answers kept insisting that the source string needs to already have escaped backslashes in it ... which isn't always the case.

Do this ..

var replaced = str.replace(String.fromCharCode(92),String.fromCharCode(92,92));