60

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!

Frankie
  • 601
  • 1
  • 5
  • 3

9 Answers9

51

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));
worpet
  • 3,788
  • 2
  • 31
  • 53
thegajman
  • 559
  • 4
  • 2
  • 3
    i do not understand why but this doesn't work for me. here is a jsfiddle, care to help. https://jsfiddle.net/a2nsL4bv/ – Timar Ivo Batis Jan 28 '19 at 11:41
  • @TimarIvoBatis , i just came across this comment of yours, you need to escape the backslash. https://stackoverflow.com/questions/8351547/backslash-in-console-log-not-appearing – Lys Mar 18 '20 at 16:51
  • 4
    Not sure why this has 49 upvotes. The `String.fromCharCode` calls are unnecessary. The problem in the question is that the string _literal_ `"This is my \string"` contains _zero_ backslashes. You can’t replace what isn’t in the string to begin with. The string variable `str` _may_ contain backslashes which then can simply be replaced like `str.replace(/\\/g, "\\\\")`, or `str.replaceAll("\\", "\\\\")`. But if you don’t get your literals correctly to begin with (as written in the question), this answer won’t help. – Sebastian Simon Jul 20 '20 at 19:05
  • The charcode list in somebody needs it : https://asecuritysite.com/coding/asc2 – Reynadan Jan 12 '23 at 11:05
50

The string doesn't contain a backslash, it contains the \s escape sequence.

var str = "This is my \\string";

And if you want a regular expression, you should have a regular expression, not a string.

var replaced = str.replace(/\\/, "\\\\");
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
13

The problem is that the \ in your first line isn't even recognized. It thinks the backslash is going to mark an escape sequence, but \s isn't an escape character, so it's ignored. Your var str is interpreted as just "This is my string". Try str.indexOf("\\") - you'll find it's -1, since there is no backslash at all. If you control the content of str, do what David says - add another \ to escape the first.

Tesserex
  • 17,166
  • 5
  • 66
  • 106
  • The problem is that I don't control the value. Its actual a windows path that I'm dealing with ( \wp-content\photos\image123.jpg ). The string is given to me as "\wp-content\photos\image123.jpg" but I can't do anything with it because the backslashes disapear. I understand they are being parsed as escape characters but I don't know how to fix it. – Frankie Mar 19 '10 at 17:41
  • 1
    Either you are getting broken JS (in which case you can't fix it) or you are getting a string in some other language and outputting it to JS without escaping special characters first, in which case you have to fix it there. – Quentin Mar 19 '10 at 17:43
  • Agreed - the only way escape sequences can get into a string is if the string is constructed in javascript. If it's coming from a form field, ajax response, query string, etc, it shouldn't need escaping. When you say "the string is given to me as..." - HOW is it actually provided to you? – Graza Mar 19 '10 at 17:51
  • @Tesserex I have try the str.indexOf("\\"), and I got a json-string, which nested a json-string with the backslash inside. It's really suck... – meadlai Oct 18 '12 at 11:00
7

var a = String.raw`This is my \string`.replace(/\\/g,"\\\\");
console.log(a);

Result:

This is my \\string
5

In case you have multiple instances or the backslash:

str.split(String.fromCharCode(92)).join(String.fromCharCode(92,92))
user2939415
  • 864
  • 1
  • 11
  • 22
1

Use this

str.replace(/(\s)/g,function($0){return $0==' '?' ':'\\s'})

or

str.replace(/ /g,'something').replace(/\s/g,'\\s').replace(/something/g,' ');

'something' it may be a combination of characters that is not in string

var str=' \s';  
  str.replace(/\s/g,'\\s'); 
// return '\\s\\s'   
  str.replace(/ /g,'SpAcE').replace(/\s/g,'\\s').replace(/SpAcE/g,' ');
// return ' \\s' 
1

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("\\","\\\\")
hasanaa
  • 11
  • 3
-1

If use case is to replace some values in the toString of a function, and convert the string back to a valid function.

var exFnStr1 = exFn.toString();

var exFnStr = "";
var quoteStarted = false;
for(i = 0; i < exFnStr1.length; i++) {
    var iChar = exFnStr1.charAt(i);
    var oChar = exFnStr1.charAt(i);
    var currentCharCode = exFnStr1.charCodeAt(i);
    if(quoteStarted) {
        if(currentCharCode === 9) oChar = "tabChar";
        if(currentCharCode === 10) oChar = "newlineChar";
    }
    //console.log(iChar+"->"+currentCharCode+"->"+oChar)
    exFnStr += oChar;

    if(currentCharCode === 34) {
        if(quoteStarted) quoteStarted = false;
        else quoteStarted = true;
    }
}
console.log(exFnStr);

//TODO - replace values in the string

exFn = new Function('return ' + exFnStr)();
Visv M
  • 431
  • 4
  • 13
-2

I haven't tried this, but the following should work

var replaced = str.replace((new RegExp("\s"),"\\s");

Essentially you don't want to replace "\", you want to replace the character represented by the "\s" escape sequence.

Unfortunately you're going to need to do this for every letter of the alphabet, every number, symbol, etc in order to cover all bases

Graza
  • 5,010
  • 6
  • 32
  • 37
  • 2
    `"\s"` is `"s"`, so this will get any other s characters too. You'd end up prefixing every character in the string with a `\` unless the sequence was a control character. – Quentin Mar 19 '10 at 20:31