Slash escape in javascript

4k views Asked by At
function slashEscape(strVar){
    var retVal = strVar;
    retVal = retVal.replace(/\\/g,"\\\\");
    return retVal;
}

I use that function to escape the slashes in a certain string. But the result is not right.

var str = slashEscape("\t \n \s");

It will result to "s" instead of "\t \n \s"

2

There are 2 answers

2
Zaenille On BEST ANSWER

When the string constant "\t \n \s" is instantiated to a JavaScript string, it transforms \t to a tab character, the \n to a new line, and \s to a s.

That's why you can't replace \ with \\ because as far as JavaScript is concerned, there is no \ character. There is only a tab character, a new line, and an s.


By the way, the result of slashEscape("\t \n \s"); is not "s". It's actually :

"    
s"

Which is a tab in the first line, a new line, then an s.

0
jamesblacklock On

To add on to what Mark Gabriel already said, it is the parser, and not any runtime code, that transforms escape sequences within your string. By the time the string is passed to your function, the parser has already removed the backslashes--they don't exist.