Space in javascript

function slashEscape(strVar){
    var retVal = strVar;
    retVal = retVal.replace(/\\/g,"\\\\");
    return retVal;
}

      

I am using this function to remove slashes in a specific string. But the result is wrong.

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

      

This will result in "s" instead of "\ t \ n \ s"

+3


source to share


2 answers


When a string constant "\t \n \s"

is created to a JavaScript string, it converts \t

to a tab character, \n

to a newline, and \s

to s

.

This is why you cannot replace \

with \\

, as there is no symbol in relation to JavaScript \

. There is only tab, newline, and s

.




By the way, the result is slashEscape("\t \n \s");

not "s"

. This is actually:

"    
s"

      

It's a tab on the first line, newline, then s.

+4


source


To add to what Mark Gabriel has already said, this is a parser, not any runtime code that converts the escape sequences to your string. When the string is passed to your function, the parser has already removed the backslash - they don't exist.



0


source







All Articles