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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4540753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:51:47  来源:igfitidea点击:

Should I use encodeURI or encodeURIComponent for encoding URLs?

javascript

提问by Aditya Shukla

Which of these two methods should be used for encoding URLs?

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

回答by Quentin

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);

回答by SLaks

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.

回答by BrianFreud

xkr.ushas a great discussion, with examples. To quote their summary:

xkr.us有一个很好的讨论,有例子。引用他们的总结:

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. 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. The best alternative is usually encodeURIComponent().

escape() will not encode: @*/+

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. 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. Note that this method does not encode the ' character, as it is a valid character within URIs.

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

Lastly, the encodeURIComponent() method should be used in most cases when encoding a single component of a URI. This method will encode certain chars that would normally be recognized as special chars for URIs so that many components may be included. Note that this method does not encode the ' character, as it is a valid character within URIs.

encodeURIComponent() will not encode: ~!*()'

escape() 方法不对 + 字符进行编码,该字符在服务器端被解释为空格,以及由字段中带有空格的表单生成。由于此缺点以及此函数无法正确处理非 ASCII 字符的事实,您应尽可能避免使用 escape()。最好的选择通常是 encodeURIComponent()。

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

使用 encodeURI() 方法比 escape() 方法更专业,因为它为 URI 编码,而不是作为 URL 一部分的查询字符串。当您需要对字符串进行编码以用于任何使用 URI 并需要某些字符保持未编码状态的资源时,请使用此方法。请注意,此方法不对 ' 字符进行编码,因为它是 URI 中的有效字符。

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

最后,在对 URI 的单个组件进行编码时,应在大多数情况下使用 encodeURIComponent() 方法。此方法将对某些通常被识别为 URI 的特殊字符的字符进行编码,以便可以包含许多组件。请注意,此方法不对 ' 字符进行编码,因为它是 URI 中的有效字符。

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

回答by Frank Wang

Here is a summary.

这是一个总结。

  1. escape() will not encode @ * _ + - . /

    Do not use it.

  2. encodeURI() will not encode A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #

    Use it when your input is a complete URL like 'https://searchexample.com/search?q=wiki'

  3. encodeURIComponent() will not encode A-Z a-z 0-9 - _ . ! ~ * ' ( ) Use it when your input is part of a complete URL e.g const queryStr = encodeURIComponent(someString)
  1. escape() 不会对 @ * _ + - 进行编码。/

    不要使用它。

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

    当您的输入是完整的 URL 时使用它,例如“ https://searchexample.com/search?q=wiki

  3. encodeURIComponent() 不会对 AZ az 0-9 - _ 进行编码。!~ * ' ( ) 当您的输入是完整 URL 的一部分时使用它,例如 const queryStr = encodeURIComponent(someString)

回答by Gopal

encodeURIComponent() : assumes that its argument is a portion (such as the protocol, hostname, path, or query string) of a URI. Therefore it escapes the punctuation characters that are used to separate the portionsof a URI.

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

encodeURI(): is used for encoding existing url

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

回答by T.Todua

Difference between encodeURIand encodeURIComponent:

encodeURI和之间的区别encodeURIComponent

encodeURIComponent(value)is mainly used to encode queryString parameter values, and it encodes every applicable character in value. encodeURIignores protocol prefix (http://) and domain name.

encodeURIComponent(value)主要用于对 queryString 参数值进行编码,它对value. 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)

来源

回答by Bob Stein

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 +              '+/@'          )

回答by Helzgate

As a general rule use 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. You can look at the other answers for the reasons why this is.

作为一般规则,使用encodeURIComponent. 不要害怕长名称,认为它的用途更具体,对我来说这是更常用的方法。也不要被吸引使用 encodeURI,因为您测试了它并且它似乎正确编码,这可能不是您打算使用的,即使您在名字字段中使用“Fred”的简单测试有效,您也会发现稍后当您使用更高级的文本(例如添加与号或主题标签)时,它将失败。您可以查看其他答案以了解原因。