对要发送到web服务器的查询字符串进行编码时-何时使用escape(),何时使用encodeURI()或encodeURIComponent():

使用转义符:

escape("% +&=");

OR

使用encodeURI()/encodeURIComponent()

encodeURI("http://www.google.com?var1=value1&var2=value2");

encodeURIComponent("var1=value1&var2=value2");

当前回答

encodeURI()-escape()函数用于javascript转义,而不是HTTP。

其他回答

还要记住,它们都编码不同的字符集,并适当地选择所需的字符集。encodeURI()比encodeURIComponent()编码更少的字符,encodeURIComponent()比escape()编码的字符更少(也不同于dannyp的观点)。

encodeURI()和encodeURIComponent()之间的差异正好是由encodeURIComponent编码的11个字符,而不是由encodeURI编码的:

我在GoogleChrome中使用console.table轻松生成了这个表,代码如下:

var arr=[];对于(变量i=0;i<256;i++){var char=字符串.fromCharCode(i);如果(encodeURI(char)==encodeURIComponent(字符)){arr.push({字符:char,encodeURI:encodeURI(char),encodeURIComponent:encodeURIComponent(char)});}}控制台.桌子(arr);

encodeURI()-escape()函数用于javascript转义,而不是HTTP。

公认的答案是好的。延伸到最后一部分:

请注意,encodeURIComponent不转义“”字符。一个普通的错误是使用它来创建html属性,例如href='MyUrl'可能会出现注射错误。如果您是从字符串,对于属性引号使用“代替”,或添加额外的编码层('可以编码为%27)。

如果您希望安全起见,也应该对百分比编码的未保留字符进行编码。

您可以使用此方法来转义它们(源代码Mozilla)

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

// fixedEncodeURIComponent("'") --> "%27"

我建议不要按原样使用这些方法中的一种。编写自己的函数来做正确的事情。

MDN给出了一个很好的url编码示例,如下所示。

var fileName = 'my file(2).txt';
var header = "Content-Disposition: attachment; filename*=UTF-8''" + encodeRFC5987ValueChars(fileName);

console.log(header); 
// logs "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"


function encodeRFC5987ValueChars (str) {
    return encodeURIComponent(str).
        // Note that although RFC3986 reserves "!", RFC5987 does not,
        // so we do not need to escape it
        replace(/['()]/g, escape). // i.e., %27 %28 %29
        replace(/\*/g, '%2A').
            // The following are not required for percent-encoding per RFC5987, 
            //  so we can allow for a little better readability over the wire: |`^
            replace(/%(?:7C|60|5E)/g, unescape);
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent