什么时候应该使用转义而不是encodeURI / encodeURIComponent?

JavaScript

LGil泡芙

2020-03-09

编码要发送到Web服务器的查询字符串时-您escape()何时使用以及何时使用encodeURI()encodeURIComponent()

使用转义:

escape("% +&=");

要么

使用encodeURI()/ encodeURIComponent()

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

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

第267篇《什么时候应该使用转义而不是encodeURI / encodeURIComponent?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

6个回答
小小西里 2020.03.09

@ johann-echavarria的答案的现代重写:

console.log(
    Array(256)
        .fill()
        .map((ignore, i) => String.fromCharCode(i))
        .filter(
            (char) =>
                encodeURI(char) !== encodeURIComponent(char)
                    ? {
                          character: char,
                          encodeURI: encodeURI(char),
                          encodeURIComponent: encodeURIComponent(char)
                      }
                    : false
        )
)

Or if you can use a table, replace console.log with console.table (for the prettier output).

逆天路易 2020.03.09

我发现即使对各种方法的各种用途和功能都有很好的了解,对各种方法进行试验也是一项很好的检查。

为此,我发现该网站对于证实我怀疑自己在做适当的事情非常有用。事实证明,它对于解码encodeURIComponent的字符串很有用,这可能很难解释。一个很棒的书签:

http://www.the-art-of-web.com/javascript/escape/

番长斯丁 2020.03.09

还要记住,它们都编码不同的字符集,并适当选择所需的字符集。encodeURI()编码的字符要少于encodeURIComponent()的编码,而encodeURIComponent()所编码的字符要比escape()少(而且与丹尼普相同)。

GilA 2020.03.09

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

nick 2020.03.09

The difference between encodeURI() and encodeURIComponent() are exactly 11 characters encoded by encodeURIComponent but not by encodeURI:

该表包含encodeURI和encodeURIComponent的十个区别

I generated this table easily with console.table in Google Chrome with this code:

var arr = [];
for(var i=0;i<256;i++) {
  var char=String.fromCharCode(i);
  if(encodeURI(char)!==encodeURIComponent(char)) {
    arr.push({
      character:char,
      encodeURI:encodeURI(char),
      encodeURIComponent:encodeURIComponent(char)
    });
  }
}
console.table(arr);

伽罗L 2020.03.09

我发现这篇文章很有启发性: Javascript Madness:查询字符串解析

当我尝试理解为什么为什么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!

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android