如何在JavaScript中转义和取消引用? [英] How to escape and unescape quotes in JavaScript?
问题描述
以下是一小段代码:
var utility = {
escapeQuotes: function(string) {
return string.replace(new RegExp('"', 'g'),'\\"');
},
unescapeQuotes: function(string) {
return string.replace(new RegExp('\\"', 'g'),'"');
}
};
var a = 'hi "';
var b = utility.escapeQuotes(a);
var c = utility.unescapeQuotes(b);
console.log(b + ' | ' + c);
我会希望这段代码有效,但结果我收到了:
I would expect this code to work, however as a result I receive:
hi \" | hi \"
如果我将unescapeQuotes方法中新的RegExp构造函数的第一个参数更改为4反斜杠一切都开始正常工作。
If I change the first parameter of the new RegExp constructor in the unescapeQuotes method to 4 backslashes everything starts working as it should.
string.replace(new RegExp('\\\\"', 'g'),'"');
结果:
hi \" | hi "
为什么需要四个反斜杠作为新RegExp构造函数的第一个参数?为什么不适用于其中只有2个吗?
推荐答案
问题是你正在使用 RegExp
构造函数,它接受一个字符串,而不是使用正则表达式文字。所以在你的unescape的这一行:
The problem is that you're using the RegExp
constructor, which accepts a string, rather than using a regular expression literal. So in this line in your unescape:
return string.replace(new RegExp('\\"', 'g'),'"');
... \\
由JavaScript解析器解释为处理字符串的部分,导致单个反斜杠被传递给正则表达式解析器。所以正则表达式解析器看到的表达式是 \
。反斜杠也是正则表达式中的转义字符,但 \
并不意味着什么特别的东西,最终只是。要在正则表达式中有一个实际的反斜杠,你必须有两个;要在字符串文字中执行此操作,您必须有四个(因此它们可以在两个解释层中存活)。
...the \\
is interpreted by the JavaScript parser as part handling the string, resulting in a single backslash being handed to the regular expression parser. So the expression the regular expression parser sees is \"
. The backslash is an escape character in regex, too, but \"
doesn't mean anything special and just ends up being "
. To have an actual backslash in a regex, you have to have two of them; to do that in a string literal, you have to have four (so they survive both layers of interpretation).
除非你有一个非常使用 RegExp
构造函数的好理由(例如,你必须使用一些不同的输入),总是使用文字形式:
Unless you have a very good reason to use the RegExp
constructor (e.g., you have to use some varying input), always use the literal form:
var utility = {
escapeQuotes: function(string) {
return string.replace(/"/g, '\\"');
},
unescapeQuotes: function(string) {
return string.replace(/\\"/g, '"');
}
};
这不会让人感到困惑。
这篇关于如何在JavaScript中转义和取消引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!