3
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
  • \t is a tab character. Your function probably should not exist; what are you trying to do? Commented Nov 26, 2014 at 4:02
  • I want the function to escape the slashes. and will output "\t \n \s" and not just "s" Commented Nov 26, 2014 at 4:04

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

does this mean I can't escape the \t and \n, ever?
this is giving me a headache haha.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.