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

使用转义符:

escape("% +&=");

OR

使用encodeURI()/encodeURIComponent()

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

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

当前回答

我有这个功能。。。

var escapeURIparam = function(url) {
    if (encodeURIComponent) url = encodeURIComponent(url);
    else if (encodeURI) url = encodeURI(url);
    else url = escape(url);
    url = url.replace(/\+/g, '%2B'); // Force the replacement of "+"
    return url;
};

其他回答

我觉得这篇文章很有启发性: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!

@johann echavarria答案的现代改写:

控制台日志(阵列(256).fill().map((忽略,i)=>String.fromCharCode(i)).过滤器((字符)=>encodeURI(char)!==encodeURIComponent(字符)? {字符:char,encodeURI:encodeURI(char),encodeURIComponent:encodeURIComponent(char)}:错误))

或者,如果可以使用表,请将console.log替换为console.table(以获得更漂亮的输出)。

我有这个功能。。。

var escapeURIparam = function(url) {
    if (encodeURIComponent) url = encodeURIComponent(url);
    else if (encodeURI) url = encodeURI(url);
    else url = escape(url);
    url = url.replace(/\+/g, '%2B'); // Force the replacement of "+"
    return url;
};

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

encodeURIComponent不编码-__!~*'(),导致以xml字符串将数据发布到php时出现问题。

例如:<xml><text x=“100”y=“150”value=“这是一个带单引号的值”/></xml>

带encodeURI的常规转义%3Cxml%3E%3Text%20x=%22100%22%20y=%22150%22%20%20value=%2它是%20a%20value%20,带有%20single%20quote%22%20/%3E%20%3C/xml%3E

您可以看到,单引号没有编码。为了解决问题,我创建了两个函数来解决项目中的问题,即编码URL:

function encodeData(s:String):String{
    return encodeURIComponent(s).replace(/\-/g, "%2D").replace(/\_/g, "%5F").replace(/\./g, "%2E").replace(/\!/g, "%21").replace(/\~/g, "%7E").replace(/\*/g, "%2A").replace(/\'/g, "%27").replace(/\(/g, "%28").replace(/\)/g, "%29");
}

对于解码URL:

function decodeData(s:String):String{
    try{
        return decodeURIComponent(s.replace(/\%2D/g, "-").replace(/\%5F/g, "_").replace(/\%2E/g, ".").replace(/\%21/g, "!").replace(/\%7E/g, "~").replace(/\%2A/g, "*").replace(/\%27/g, "'").replace(/\%28/g, "(").replace(/\%29/g, ")"));
    }catch (e:Error) {
    }
    return "";
}