Que*_*tin 300
这取决于你实际想做什么.
encodeURI假定输入是一个完整的URI,可能包含一些需要编码的字符.
encodeURIComponent将对具有特殊含义的所有内容进行编码,因此您可以将其用于URI的组件,例如
var world = "A string with symbols & characters that have special meaning?";
var uri = 'http://example.com/foo?hello=' + encodeURIComponent(world);
Run Code Online (Sandbox Code Playgroud)
SLa*_*aks 98
如果您要编码一个字符串以放入一个URL组件(一个查询字符串参数),您应该调用encodeURIComponent.
如果您要编码现有网址,请致电encodeURI.
Bri*_*eud 46
xkr.us有一个很好的讨论,有例子.引用他们的摘要:
escape()方法不对+字符进行编码,该字符被解释为服务器端的空间以及由其字段中具有空格的表单生成.由于这个缺点以及此函数无法正确处理非ASCII字符的事实,您应该尽可能避免使用escape().最好的选择通常是encodeURIComponent().
escape()不会编码:@*/+
使用encodeURI()方法比escape()更专业,因为它编码URI而不是查询字符串,后者是URL的一部分.当您需要对要用于任何使用URI并且需要某些字符保持未编码的资源的字符串进行编码时,请使用此方法.请注意,此方法不对'字符进行编码,因为它是URI中的有效字符.
encodeURI()不会编码:〜!@#$&*()=:/,;?+'
最后,在编码URI的单个组件时,大多数情况下应使用encodeURIComponent()方法.此方法将编码某些字符,这些字符通常被识别为URI的特殊字符,因此可以包含许多组件.请注意,此方法不对'字符进行编码,因为它是URI中的有效字符.
encodeURIComponent()不会编码:〜!*()'
小智 12
这是一个摘要。
escape()不会对@ * _ +-进行编码。/
不要使用它。
encodeURI()不会对AZ az 0-9进行编码;,/?:@&= + $-_。!〜*'()#
当您输入的是完整网址(例如“ https://searchexample.com/search?q=wiki ”)时,请使用它
const queryStr = encodeURIComponent(someString)小智 9
encodeURIComponent():假定其参数是URI的一部分(例如协议,主机名,路径或查询字符串).因此,它会转义用于分隔URI部分的标点字符.
encodeURI():用于编码现有的url
encodeURI和encodeURIComponent用于不同的目的。
一些区别是
encodeURI用于编码完整的 URL,而encodeURIComponent用于编码 URI 组件,例如查询字符串。
有11 个字符不是由 encodeURI 编码的,而是由 encodeURIComponent 编码的。列表:
| 特点 | 编码URI | 编码URI组件 |
|---|---|---|
| # | # | %23 |
| $ | $ | %24 |
| & | & | %26 |
| + | + | %2B |
| , | , | %2C |
| / | / | %2F |
| : | : | %3A |
| ; | ; | %3B |
| = | = | %3D |
| ? | ? | %3F |
| @ | @ | %40 |
注意:
encodeURIComponent 不编码 -_.!~*'()。如果要对这些字符进行编码,则必须将它们替换为相应的 UTF-8 字符序列
如果您想了解有关 encodeURI 和 encodeURIComponent 的更多信息,请查看参考链接。 参考链接
encodeURI和之间的区别encodeURIComponent:encodeURIComponent(value)主要是用于编码queryString参数值,并将它编码在每一个适用的字符value。 encodeURI忽略协议前缀(http://)和域名。
在非常非常少见的情况下,当您想实现手动编码来对其他字符进行编码(尽管在典型情况下不需要对其他字符进行编码)时! *,可以使用:
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
Run Code Online (Sandbox Code Playgroud)
(来源)
其他答案描述了目的。以下是每个函数实际转换的字符:
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 + ' "%<>[\\]^`{|}' + '#$&,:;=?' + "!'()~")
Run Code Online (Sandbox Code Playgroud)
以上所有字符均转换为百分比十六进制代码。空格 to %20、百分号 to%25等。下面的字符不变地通过。
以下是函数不会转换的字符:
pass_thru = '*-._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
encodeURI (pass_thru + '#$&,:;=?' + '+/@' + "!'()~")
encodeURIComponent(pass_thru + "!'()~")
escape (pass_thru + '+/@' )
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
125571 次 |
| 最近记录: |