Javascript在字符串中转义反斜杠

时间:2015-05-12 13:47:05

标签: javascript

我尝试在Chrome控制台中运行以下代码

var line = "RewriteRule ^research/research\-facilities/library\.html$ http://test.com [R=301,L]";

var tmp = line.replace(/\\/g, "\\");

console.log(tmp);

输出结果为:

RewriteRule ^research/research-facilities/library.html$ http://test.com [R=301,L]

我需要的输出是:

RewriteRule ^research/research\\-facilities/library\\.html$ http://test.com [R=301,L]

有谁知道如何解决它?

1 个答案:

答案 0 :(得分:1)

您遇到的问题是您的字符串:

"RewriteRule ^research/research\-facilities/library\.html$ http://test.com [R=301,L]"

的值为:

RewriteRule ^research/research-facilities/library.html$ http://test.com [R=301,L]

字符串中的反斜杠字符会转义下一个字符。对于具有其他含义的字符,它们代表其他字符,例如"\n"表示换行符。对于任何其他字符,将删除转义字符。

这意味着'\-'的值为'-''\.'的值为'.'

如果希望字符串包含正确的转义字符,则需要以这种方式编写它。

如果您希望字符串的为:

RewriteRule ^research/research\-facilities/library\.html$ http://test.com [R=301,L]

原始字符串应为:

"RewriteRule ^research/research\\-facilities/library\\.html$ http://test.com [R=301,L]"