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"
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.