在JavaScript中,
之间有什么区别答案 0 :(得分:49)
对于视觉敏锐的人,这里有一张表格,显示encodeURI
,encodeURIComponent
和escape
对常用符号ASCII字符的影响:
Char encUrI encURIComp escape
* * * *
. . . .
_ _ _ _
- - - -
~ ~ ~ %7E
' ' ' %27
! ! ! %21
( ( ( %28
) ) ) %29
/ / %2F /
+ + %2B +
@ @ %40 @
? ? %3F %3F
= = %3D %3D
: : %3A %3A
# # %23 %23
; ; %3B %3B
, , %2C %2C
$ $ %24 %24
& & %26 %26
%20 %20 %20
% %25 %25 %25
^ %5E %5E %5E
[ %5B %5B %5B
] %5D %5D %5D
{ %7B %7B %7B
} %7D %7D %7D
< %3C %3C %3C
> %3E %3E %3E
" %22 %22 %22
\ %5C %5C %5C
| %7C %7C %7C
` %60 %60 %60
另一个重要区别是unescape不处理多字节UTF-8序列,而decodeURI [组件]则执行:
decodeURIComponent("%C3%A9") == "é"
unescape("%C3%A9") == "é"
答案 1 :(得分:40)
escape
- 已损坏,已弃用,请勿使用encodeURI
- 对URL中不允许(原始)的字符进行编码(如果您事先无法修复,请使用它来修复损坏的URI)encodeURIComponent
- 作为encodeURI
加上URI中具有特殊含义的字符(用于编码数据以插入URI)答案 2 :(得分:21)
首先 - 不推荐使用Escape,不应使用它。
<强>是encodeURI()强>
当您想对URL进行编码时,您应该使用它,它会对URL中不允许的符号进行编码。
<强> encodeURIComponent方法()强>
当您想要对URL的参数进行编码时,您可以使用它来编码整个URL。但你必须解码才能再次使用它。
-
我说这是重复的。这是关于SO的一个很好的答案 - 致Arne Evertsson的积分: When are you supposed to use escape instead of encodeURI / encodeURIComponent?
关于为什么/为什么不在这个主题上有很多细节。
答案 3 :(得分:5)
//This is expected result
//Result array with mark of value at needed position
array:32 [▼
"ID" => "7917"
"ProvinceCode" => "MB"
"Create" => "2016-05-18 18:16:26.790"
"DayOfTheWeek" => "4"
"Giai1" => "28192"
"Giai2" => "83509"
"Giai3" => "51911-02858"
"Giai4" => "14102-97270-96025-08465-89047-45904"
"Giai5" => "7892-9140-x4y069-8499"
"Giai6" => "6117-7471-5541-9119-4855-0566"
"Giai7" => "843-860-023"
"Giai8" => "71-13-55-89"
"Giai9" => ""
"Status" => "1"
]
- 已弃用,您不应该使用。
escape
- 替换除了
之外的所有字符
encodeURI
; , / ? : @ & = + $ - _ . ! ~ * ' ( ) # a-z 0-9
- 替换除了encodeURIComponent
答案 4 :(得分:0)
只需自己尝试encodeURI()
和encodeURIComponent()
...
console.log(encodeURIComponent('@#$%^&*'));
输入:@#$%^&*
。输出:%40%23%24%25%5E%26*
。那么,等等,*
怎么了?为什么不转换呢? TLDR:您实际上想要fixedEncodeURIComponent()
和fixedEncodeURI()
。长篇小说...
escape()
: 请勿使用! 引用MDN escape()
Documentation ... 警告:尽管并未严格建议使用escape()(如“从Web标准中删除”),但它是在ECMA-262标准的附件B中定义的,其介绍如下:
...编写新的ECMAScript代码时,程序员不应使用或假定这些功能和行为存在。...
encodeURI()
: 请勿使用! 使用fixedEncodeURI()
。引用MDN encodeURI()
Documentation ... 如果希望遵循URL的最新RFC3986,这会保留方括号(用于IPv6),因此在形成可能属于URL的内容(例如主机)时未进行方括号编码,则以下代码段可能帮助:
function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }
encodeURIComponent()
: 请勿使用! 使用fixedEncodeURIComponent()
。引用MDN encodeURIComponent() Documentation ... 为了严格遵守RFC 3986(保留!,',(,)和*),即使这些字符没有正式的URI分隔用法,也可以安全地使用以下字符:
function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }
然后可以简化问题:fixedEncodeURI()
和fixedEncodeURIComponent()
有什么区别? fixedEncodeURIComponent()
编码以下字符,而fixedEncodeURI()
不编码:+@?=:#;,$&
。