JavaScrip 转码与解码——0710

一、escape 和 unescape

escape()不能直接用于URL编码,它的真正作用是返回一个字符的Unicode编码值。
如果只是编码字符串,可以用escape()
escape不编码字符有69个:*,+,-,.,/,@,_,0-9,a-z,A-Z。

	//转码
    console.log(escape("张三"));  //%u5F20%u4E09
    //解码
    console.log(unescape(escape("张三")));   //张三

二、encodeURI 和 decodeURI

把URI字符串采用UTF-8编码格式转化成escape各式的字符串。

encodeURI不编码字符有82个:!,#,$,&,’,(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a-z,A-Z

encodeURI()用于整个url编码。

    var str="http://www.maodou.com?name=张三&age=20";
    //转码
    console.log(encodeURI(str));   //http://www.maodou.com?name=%E5%BC%A0%E4%B8%89&age=20
    //解码
    console.log(decodeURI(encodeURI(str)));  //http://www.maodou.com?name=张三&age=20

三、encodeURIComponent 和 decodeURIComponent

与encodeURI()的区别是,它用于对URL的组成部分进行个别编码,而不用于对整个URL进行编码。

因此,"; / ? : @ & = + $ , #",这些在encodeURI()中不被编码的符号,在encodeURIComponent()中统统会被编码。至于具体的编码方法,两者是一样。把URI字符串采用UTF-8编码格式转化成escape格式的字符串。

encodeURIComponent() 用于参数的传递,参数包含特殊字符可能会造成间断。所以当需要编码URL中的参数的时候,使用 encodeURIComponent()。

    //转码
    console.log(encodeURIComponent(str));  //http%3A%2F%2Fwww.maodou.com%3Fname%3D%E5%BC%A0%E4%B8%89%26age%3D20
    //解码
    console.log(decodeURIComponent(encodeURIComponent(str)));  //http://www.maodou.com?name=张三&age=20

encodeURI方法不会对下列字符编码:
ASCII字母 数字 ~!@#$&()=:/,;?+’
encodeURIComponent方法不会对下列字符编码:
ASCII字母 数字 ~!
()’
所以encodeURIComponentencodeURI编码的范围更大。

四、Base64转码解码

Base64转码的对象只能是字符串,并且是对Unicode转码,不支持中文。

(1)window 对象上可以访问到base64编码和解码的方法,直接调用即可。

	//转码
    console.log(window.btoa("abc122Af"));  //YWJjMTIyQWY=
    //解码
    console.log(window.atob("YWJjMTIyQWY="));  //abc122Af
	//对汉字进行转码
    console.log(window.btoa(escape("张三")));  //JXU1RjIwJXU0RTA5
    //解码
    console.log(unescape(window.atob("JXU1RjIwJXU0RTA5")));  //张三

(2)除以上方式外,也可以引入一个 base64.js 文件,使用 Base64 对象里边转码解码的方法,如下所示:

<script src="base64.js"></script>
<script>
    console.log(Base64);
    console.log(Base64.btoa("abc122Af"));  //YWJjMTIyQWY=
    console.log(Base64.atob("YWJjMTIyQWY="));  //abc122Af
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值