对要发送到web服务器的查询字符串进行编码时-何时使用escape(),何时使用encodeURI()或encodeURIComponent():
使用转义符:
escape("% +&=");
OR
使用encodeURI()/encodeURIComponent()
encodeURI("http://www.google.com?var1=value1&var2=value2");
encodeURIComponent("var1=value1&var2=value2");
公认的答案是好的。延伸到最后一部分:
请注意,encodeURIComponent不转义“”字符。一个普通的错误是使用它来创建html属性,例如href='MyUrl'可能会出现注射错误。如果您是从字符串,对于属性引号使用“代替”,或添加额外的编码层('可以编码为%27)。
如果您希望安全起见,也应该对百分比编码的未保留字符进行编码。
您可以使用此方法来转义它们(源代码Mozilla)
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
// fixedEncodeURIComponent("'") --> "%27"
我觉得这篇文章很有启发性:Javascript疯狂:查询字符串解析
当我试图解释为什么decodeURIComponent不能正确解码“+”时,我发现了这一点。以下是摘录:
String: "A + B"
Expected Query String Encoding: "A+%2B+B"
escape("A + B") = "A%20+%20B" Wrong!
encodeURI("A + B") = "A%20+%20B" Wrong!
encodeURIComponent("A + B") = "A%20%2B%20B" Acceptable, but strange
Encoded String: "A+%2B+B"
Expected Decoding: "A + B"
unescape("A+%2B+B") = "A+++B" Wrong!
decodeURI("A+%2B+B") = "A+++B" Wrong!
decodeURIComponent("A+%2B+B") = "A+++B" Wrong!