这两种方法中应该使用哪一种来编码url ?


当前回答

encodeURI和encodeURIComponent的区别:

encodeURIComponent(value)主要用于编码queryString参数值,它对value中每个适用的字符进行编码。encodeURI忽略协议前缀(http://)和域名)。


在非常非常罕见的情况下,当你想实现手动编码来编码额外的字符时(尽管在典型情况下不需要编码),例如:!*,则 你可以用:

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

(源)

其他回答

encodeURI和encodeURIComponent的区别:

encodeURIComponent(value)主要用于编码queryString参数值,它对value中每个适用的字符进行编码。encodeURI忽略协议前缀(http://)和域名)。


在非常非常罕见的情况下,当你想实现手动编码来编码额外的字符时(尽管在典型情况下不需要编码),例如:!*,则 你可以用:

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

(源)

其他答案描述了目的。下面是每个函数实际转换的字符:

control = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F'
        + '\x10\x11\x12\x13\x14\X15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F'
                                                                    + '\x7F'
encodeURI         (control + ' "%<>[\\]^`{|}'                             )
encodeURIComponent(control + ' "%<>[\\]^`{|}' + '#$&,:;=?' + '+/@'        )
escape            (control + ' "%<>[\\]^`{|}' + '#$&,:;=?' +       "!'()~")

以上所有字符都转换为百分制16进制代码。空格到%20,百分比到%25,等等。下面的字符没有改变。

以下是函数不会转换的字符:

pass_thru = '*-._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'

encodeURI         (pass_thru + '#$&,:;=?' + '+/@' + "!'()~")
encodeURIComponent(pass_thru +                      "!'()~")
escape            (pass_thru +              '+/@'          )

以下是摘要。

Escape()不会编码@ * _ + -。/ 不要使用它。 encodeURI()不会编码A-Z A-Z 0-9;, / ?: @ & = + $ - _。! ~ * ' () # 当你的输入是一个完整的URL,如“https://searchexample.com/search?q=wiki”时使用它 encodeURIComponent()不会编码A-Z A-Z 0-9 - _。! ~ * ' () 当您的输入是完整URL的一部分时使用它 如 const queryStr = encodeURIComponent(someString)

encodeURI和encodeURIComponent用于不同的目的。 一些不同之处在于

encodeURI用于编码完整的URL,而encodeURIComponent用于编码URI组件,例如查询字符串。 有11个字符不是由encodeURI编码的,而是由encodeURIComponent编码的。 列表:

Character encodeURI encodeURIComponent
# # %23
$ $ %24
& & %26
+ + %2B
, , %2C
/ / %2F
: : %3A
; ; %3B
= = %3D
? ? %3F
@ @ %40

注: encodeURIComponent不编码-_.!~*'()。如果要对这些字符进行编码,则必须将它们替换为相应的UTF-8序列字符

如果您想了解更多关于encodeURI和encodeURIComponent的信息,请查看参考链接。 参考链接

encodeURIComponent():假设它的参数是一个部分(比如协议、主机名、路径或查询字符串) URI的。因此,它转义了用于分隔URI部分的标点符号。

encodeURI():用于对已有url进行编码