概述:
1、escape:对字符串编码
;unescape:解码
2、encodeURI和encodeURIComponent 对URL进行编码
3、encodeURI <-- 编码范围小于 --> encodeURIComponent
一、escape和它们不是同一类
escape是对字符串(string)进行编码(而另外两种是对URL),作用是让它们在所有电脑上可读。
编码之后的效果是%XX或者%uXXXX这种形式。
其中 ASCII字母、数字、@*/+ ,这几个字符不会被编码,其余的都会。
二、最常用的encodeURI和encodeURIComponent
它们都是编码URL,唯一区别就是编码的字符范围
encodeURI:不会
对下列字符编码 ASCII字母、数字、~!@#$&*()=:/,;?+'
encodeURIComponent:不会
对下列字符编码 ASCII字母、数字、~!*()'
所以encodeURIComponent比encodeURI编码的范围更大。
三、最重要的,我该什么场合用什么方法
1、如果只是编码字符串,那么用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肯定要出问题,因为后面的/是需要编码的。
援引:http://www.cnblogs.com/season-huang/p/3439277.html
四、btoa & atob
1.javascript ----> Base64转码
var str = 'javascript';
window.btoa(str)
//转码结果 "amF2YXNjcmlwdA=="
window.atob("amF2YXNjcmlwdA==")
//解码结果 "javascript"
2.Base64转码的对象只能是字符串,不能低Unicode转码。
var str = "China,中国"
window.btoa(str);
报错:Uncaught DOMException: Failed to execute 'btoa' on 'Window':
The string to be encoded contains characters outside of the Latin1 range.
对于汉字,这就要使用window.encodeURIComponent
和window.decodeURIComponent
var str = "China,中国";
window.btoa(window.encodeURIComponent(str))
//"Q2hpbmElRUYlQkMlOEMlRTQlQjglQUQlRTUlOUIlQkQ="
window.decodeURIComponent(window.atob('Q2hpbmElRUYlQkMlOEMlRTQlQjglQUQlRTUlOUIlQkQ='))
//"China,中国"