简体   繁体   English

我应该使用 encodeURI 还是 encodeURIComponent 来编码 URL?

[英]Should I use encodeURI or encodeURIComponent for encoding URLs?

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

It depends on what you are actually wanting to do.这取决于您实际想要做什么。

encodeURI assumes that the input is a complete URI that might have some characters which need encoding in it. encodeURI 假设输入是一个完整的 URI,其中可能包含一些需要编码的字符。

encodeURIComponent will encode everything with special meaning, so you use it for components of URIs such as encodeURIComponent 将对具有特殊含义的所有内容进行编码,因此您可以将其用于 URI 的组件,例如

var world = "A string with symbols & characters that have special meaning?";
var uri = 'http://example.com/foo?hello=' + encodeURIComponent(world);

If you're encoding a string to put in a URL component (a querystring parameter), you should call encodeURIComponent .如果您要对字符串进行编码以放入 URL 组件(查询字符串参数),则应调用encodeURIComponent

If you're encoding an existing URL, call encodeURI .如果要对现有 URL 进行编码,请调用encodeURI

xkr.us has a great discussion, with examples. xkr.us有一个很好的讨论,有例子。 To quote their summary:引用他们的总结:

The escape() method does not encode the + character which is interpreted as a space on the server side as well as generated by forms with spaces in their fields. escape() 方法不对 + 字符进行编码,该字符在服务器端被解释为空格,以及由字段中带有空格的表单生成。 Due to this shortcoming and the fact that this function fails to handle non-ASCII characters correctly, you should avoid use of escape() whenever possible.由于此缺点以及此函数无法正确处理非 ASCII 字符的事实,您应尽可能避免使用 escape()。 The best alternative is usually encodeURIComponent().最好的选择通常是 encodeURIComponent()。

escape() will not encode: @*/+ escape() 不会编码:@*/+

Use of the encodeURI() method is a bit more specialized than escape() in that it encodes for URIs as opposed to the querystring, which is part of a URL.使用 encodeURI() 方法比 escape() 方法更专业,因为它为 URI 编码,而不是作为 URL 一部分的查询字符串。 Use this method when you need to encode a string to be used for any resource that uses URIs and needs certain characters to remain un-encoded.当您需要对字符串进行编码以用于任何使用 URI 并需要某些字符保持未编码状态的资源时,请使用此方法。 Note that this method does not encode the ' character, as it is a valid character within URIs.请注意,此方法不对 ' 字符进行编码,因为它是 URI 中的有效字符。

encodeURI() will not encode: ~!@#$&*()=:/,;?+' encodeURI() 不会编码:~!@#$&*()=:/,;?+'

Lastly, the encodeURIComponent() method should be used in most cases when encoding a single component of a URI.最后,在对 URI 的单个组件进行编码时,应在大多数情况下使用 encodeURIComponent() 方法。 This method will encode certain chars that would normally be recognized as special chars for URIs so that many components may be included.此方法将对某些通常被识别为 URI 的特殊字符的字符进行编码,以便可以包含许多组件。 Note that this method does not encode the ' character, as it is a valid character within URIs.请注意,此方法不对 ' 字符进行编码,因为它是 URI 中的有效字符。

encodeURIComponent() will not encode: ~!*()' encodeURIComponent() 不会编码:~!*()'

Here is a summary.这是一个总结。

  1. escape() will not encode @ * _ + - . escape() 不会对 @ * _ + - 进行编码。 / /

    Do not use it.不要使用它。

  2. encodeURI() will not encode AZ az 0-9 ; encodeURI() 不会对 AZ az 0-9 进行编码; , / ? , / ? : @ & = + $ - _ . :@ & = + $ - _ 。 ! ~ * ' ( ) # ~ * ' ( ) #

    Use it when your input is a complete URL like ' https://searchexample.com/search?q=wiki '当您的输入是完整的 URL 时使用它,例如“ https://searchexample.com/search?q=wiki

  3. encodeURIComponent() will not encode AZ az 0-9 - _ . encodeURIComponent() 不会对 AZ az 0-9 - _ 进行编码。 ! ~ * ' ( ) Use it when your input is part of a complete URL eg const queryStr = encodeURIComponent(someString) ~ * ' ( ) 当您的输入是完整 URL 的一部分时使用它,例如const queryStr = encodeURIComponent(someString)

encodeURI and encodeURIComponent are used for different purposes. encodeURIencodeURIComponent用于不同的目的。
Some of the difference are一些区别是

  1. encodeURI is used to encode a full URL whereas encodeURIComponent is used for encoding a URI component such as a query string. encodeURI用于编码完整的 URL,encodeURIComponent用于编码 URI 组件,例如查询字符串。

  2. There are 11 characters which are not encoded by encodeURI, but encoded by encodeURIComponent.11 个字符不是由 encodeURI 编码的,而是由 encodeURIComponent 编码的。 List:列表:

Character特点 encodeURI编码URI encodeURIComponent编码URI组件
# # # # %23 %23
$ $ $ $ %24 %24
& & & & %26 %26
+ + + + %2B %2B
, , , , %2C %2C
/ / / / %2F %2F
: : %3A %3A
; ; ; ; %3B %3B
= = = = %3D %3D
? ? ? ? %3F %3F
@ @ @ @ %40 %40

Notes:笔记:
encodeURIComponent does not encode -_.!~*'(). encodeURIComponent不编码 -_.!~*'()。 If you want to these characters are encoded, you have to replace them with a corresponding UTF-8 sequence of characters如果要对这些字符进行编码,则必须将它们替换为相应的 UTF-8 字符序列

If you want to learn more about encodeURI and encodeURIComponent, please check the reference link.如果您想了解有关 encodeURI 和 encodeURIComponent 的更多信息,请查看参考链接。 Reference Link参考链接

encodeURIComponent() : assumes that its argument is a portion (such as the protocol, hostname, path, or query string) of a URI. encodeURIComponent() :假定其参数是 URI 的一部分(例如协议、主机名、路径或查询字符串)。 Therefore it escapes the punctuation characters that are used to separate the portionsof a URI.因此,它会转义用于分隔 URI 部分的标点字符。

encodeURI(): is used for encoding existing url encodeURI(): 用于对现有 url 进行编码

Difference between encodeURI and encodeURIComponent : encodeURIencodeURIComponent区别:

encodeURIComponent(value) is mainly used to encode queryString parameter values, and it encodes every applicable character in value . encodeURIComponent(value)主要用于对 queryString 参数值进行编码,并对value每个适用字符进行编码。 encodeURI ignores protocol prefix ( http:// ) and domain name. encodeURI忽略协议前缀 ( http:// ) 和域名。


In very, very rare cases, when you want to implement manual encoding to encode additional characters (though they don't need to be encoded in typical cases) like: ! *在非常,非常罕见的情况下,如果你想实现手动编码来对其他字符(尽管他们并不需要典型案件要被编码的那样),如: ! * ! * , then you might use: ! * ,那么你可以使用:

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

( source ) 来源

Other answers describe the purposes.其他答案描述了目的。 Here are the characters each function will actually convert :以下是每个函数实际转换的字符:

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 + ' "%<>[\\]^`{|}' + '#$&,:;=?' +       "!'()~")

All characters above are converted to percent-hexadecimal codes.以上所有字符都转换为百分比十六进制代码。 Space to %20 , percent to %25 , etc. The characters below pass through unchanged.空格到%20 ,百分比到%25等等。下面的字符通过不变。

Here are the characters the functions will NOT convert :以下是函数不会转换的字符:

pass_thru = '*-._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'

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

As a general rule use encodeURIComponent .作为一般规则,使用encodeURIComponent Don't be scared of the long name thinking it's more specific in it's use, to me it's the more commonly used method.不要害怕长名称,认为它的用途更具体,对我来说这是更常用的方法。 Also don't be suckered into using encodeURI because you tested it and it appears to be encoding properly, it's probably not what you meant to use and even though your simple test using "Fred" in a first name field worked, you'll find later when you use more advanced text like adding an ampersand or a hashtag it will fail.也不要被吸引使用 encodeURI,因为您测试了它并且它似乎正确编码,这可能不是您打算使用的,即使您在名字字段中使用“Fred”的简单测试有效,您也会发现稍后当您使用更高级的文本(例如添加与号或主题标签)时,它将失败。 You can look at the other answers for the reasons why this is.您可以查看其他答案以了解原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM