简体   繁体   English

在javascript中删除逃脱

[英]Slash escape in javascript

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" 这将导致“s”而不是“\\ 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 . 当字符串常量"\\t \\n \\s"实例化为 JavaScript字符串时,它将\\t转换为制表符,将\\n转换为新行,将\\s转换为s

That's why you can't replace \\ with \\\\ because as far as JavaScript is concerned, there is no \\ character. 这就是为什么你不能替换\\\\\\因为就如JavaScript而言,没有任何\\字符。 There is only a tab character, a new line, and an s . 只有制表符,新行和s


By the way, the result of slashEscape("\\t \\n \\s"); 顺便说一句, slashEscape("\\t \\n \\s");的结果slashEscape("\\t \\n \\s"); is not "s" . 不是 "s" It's actually : 它实际上是:

"    
s"

Which is a tab in the first line, a new line, then an s. 这是第一行中的选项卡,新行,然后是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. 要添加Mark Gabriel已经说过的内容,它是解析器 ,而不是任何运行时代码,它可以转换字符串中的转义序列。 By the time the string is passed to your function, the parser has already removed the backslashes--they don't exist. 当字符串传递给您的函数时,解析器已经删除了反斜杠 - 它们不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM