escape,encodeURI,encodeURIComponent的区别
来源:互联网 发布:java 读取日志文件 编辑:程序博客网 时间:2024/05/16 04:05
一、escape和它们不是同一类
对URL编码是常见的事,所以这两个方法应该是实际中要特别注意的。
它们都是编码URL,唯一区别就是编码的字符范围,其中
encodeURI方法不会对下列字符编码 ASCII字母 数字 ~!@#$&*()=:/,;?+'
encodeURIComponent方法不会对下列字符编码 ASCII字母 数字 ~!*()'
所以encodeURIComponent比encodeURI编码的范围更大。
实际例子来说,encodeURIComponent会把 http:// 编码成 http%3A%2F%2F 而encodeURI却不会。
三、最重要的,什么场合应该用什么方法
1、如果只是编码字符串,不和URL有半毛钱关系,那么用escape。
2、如果你需要编码整个URL,然后需要使用这个URL,那么用encodeURI。
比如
编码后会变为
看到了把,参数中的 "/" 可以编码,如果用encodeURI肯定要出问题,因为后面的/是需要编码的。
简单来说,escape是对字符串(string)进行编码(而另外两种是对URL),作用是让它们在所有电脑上可读。
编码之后的效果是%XX或者%uXXXX这种形式。
其中 ASCII字母 数字 @*/+ 这几个字符不会被编码,其余的都会。
最关键的是,当你需要对URL编码时,请忘记这个方法,这个方法是针对字符串使用的,不适用于URL。
二、最常用的encodeURI和encodeURIComponent
对URL编码是常见的事,所以这两个方法应该是实际中要特别注意的。
它们都是编码URL,唯一区别就是编码的字符范围,其中
encodeURI方法不会对下列字符编码 ASCII字母 数字 ~!@#$&*()=:/,;?+'
encodeURIComponent方法不会对下列字符编码 ASCII字母 数字 ~!*()'
所以encodeURIComponent比encodeURI编码的范围更大。
实际例子来说,encodeURIComponent会把 http:// 编码成 http%3A%2F%2F 而encodeURI却不会。
三、最重要的,什么场合应该用什么方法
1、如果只是编码字符串,不和URL有半毛钱关系,那么用escape。
2、如果你需要编码整个URL,然后需要使用这个URL,那么用encodeURI。
比如
encodeURI("http://www.cnblogs.com/season-huang/some other thing");
编码后会变为
"http://www.cnblogs.com/season-huang/some%20other%20thing";
其中,空格被编码成了%20。但是如果你用了encodeURIComponent,那么结果变为
"http%3A%2F%2Fwww.cnblogs.com%2Fseason-huang%2Fsome%20other%20thing"
看到了区别吗,连 "/" 都被编码了,整个URL已经没法用了。
3、当你需要编码URL中的参数的时候,那么encodeURIComponent是最好方法。
var param = "http://www.cnblogs.com/season-huang/"; //param为参数param = encodeURIComponent(param);var url = "http://www.cnblogs.com?next=" + param;console.log(url) //"http://www.cnblogs.com?next=http%3A%2F%2Fwww.cnblogs.com%2Fseason-huang%2F"
看到了把,参数中的 "/" 可以编码,如果用encodeURI肯定要出问题,因为后面的/是需要编码的。
=======================================
原文链接:https://www.zhihu.com/question/21861899/answer/20300871
0 0
- escape,encodeURI,encodeURIComponent的区别
- escape, encodeURI, encodeURIComponent的区别
- escape,encodeURI,encodeURIComponent的区别
- escape() encodeURI() encodeURIComponent()区别
- escape()、encodeURI()、encodeURIComponent()区别
- escape encodeuri encodeURIComponent 区别
- escape、encodeURI、encodeURIComponent等方法的区别
- escape、encodeURI、encodeURIComponent等方法的区别
- escape,encodeURI及encodeURIComponent的区别?
- escape、encodeURI、encodeURIComponent等方法的区别
- escape、encodeURI、encodeURIComponent等方法的区别
- escape、encodeURI、encodeURIComponent等方法的区别
- escape、encodeURI 和encodeURIComponent 的区别
- JS的Escape,encodeURI,encodeURIComponent区别
- js中escape,encodeURI,encodeURIComponent的区别
- escape、encodeURI、encodeURIComponent等方法的区别
- escape、encodeURI、encodeURIComponent等方法的区别
- escape、encodeURI、encodeURIComponent 方法的区别
- jdbc连接数据库
- JS中const、let、var之间的区别
- PAT 乙级 1027. 打印沙漏(20) Java版
- Android Studio 的一些设置
- UVa-202
- escape,encodeURI,encodeURIComponent的区别
- ADC的有效位数和信纳比计算
- Redux中的actions
- C 语言中&&,||,&,|的区别
- js 判断元素在数组中和取反操作
- 逆波兰表达式,走一波
- 论文笔记(一)Deep Ranking for Person Re-Identification via Joint Representation Learning
- Linux学习之:创建逻辑卷管理(LVM)
- Dubbo整合Spring时jar包冲突问题