JS 转码 escape、encodeURI 、encodeURIComponent

1、 escape 和 unescape

  • escape() 函数可对字符串进行编码,这样就可以在所有的计算机上读取该字符串
  • 该方法不会对 ASCII 字母和数字进行编码,也不会对下面这些 ASCII 标点符号进行编码: * @ - _ + . / 。其他所有的字符都会被转义序列替换
输入:
<script type="text/javascript">

    document.write(escape("Visit W3School!") + "<br />")
    document.write(escape("?!=()#%&"))

</script>

输出结果: 
Visit%20W3School%21
%3F%21%3D%28%29%23%25%26
  • unescape() 函数可对通过 escape() 编码的字符串进行解码。
  • ECMAScript v3 已从标准中删除了 unescape() 函数,并反对使用它,因此应该用 decodeURI() 和 decodeURIComponent() 取而代之

2、encodeURI 和 decodeURI

  • encodeURI() 函数可把字符串作为 URI 进行编码
  • 该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ’ ( )
  • 目的是对 URI 进行完整的编码,因此对以下在 URI 中具有特殊含义的 ASCII 标点符号,encodeURI() 函数是不会进行转义的:;/?:@&=+$,#
  • 如果 URI 组件中含有分隔符,比如 ? 和 #,则应当使用 encodeURIComponent() 方法分别对各组件进行编码
输入:
<script type="text/javascript">

    document.write(encodeURI("http://www.w3school.com.cn")+ "<br />")
    document.write(encodeURI("http://www.w3school.com.cn/My first/"))
    document.write(encodeURI(",/?:@&=+$#"))

</script>

输出结果:
    http://www.w3school.com.cn
    http://www.w3school.com.cn/My%20first/
    ,/?:@&=+$#
  • decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码;
  • decodeURI() 函数参数 为:URIstring
输入:
<script type="text/javascript">

    var test1="http://www.w3school.com.cn/My first/"

    document.write(encodeURI(test1)+ "<br />")
    document.write(decodeURI(test1))

</script>

输出结果: 
    http://www.w3school.com.cn/My%20first/
    http://www.w3school.com.cn/My first/

3、encodeURIComponent 和 decodeURIComponent

  • encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。
  • 该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ’ ( )
  • 其他字符(比如 :;/?:@&=+$,# 这些用于分隔 URI 组件的标点符号),都是由一个或多个十六进制的转义序列替换的
  • 请注意 encodeURIComponent() 函数 与 encodeURI() 函数的区别之处,前者假定它的参数是 URI 的一部分(比如协议、主机名、路径或查询字符串)。因此 encodeURIComponent() 函数将转义用于分隔 URI 各个部分的标点符号
输入:
<script type="text/javascript">

    document.write(encodeURIComponent("http://www.w3school.com.cn"))
    document.write("<br />")
    document.write(encodeURIComponent("http://www.w3school.com.cn/p 1/"))
    document.write("<br />")
    document.write(encodeURIComponent(",/?:@&=+$#"))

</script>

输出结果:
    http%3A%2F%2Fwww.w3school.com.cn
    http%3A%2F%2Fwww.w3school.com.cn%2Fp%201%2F
    %2C%2F%3F%3A%40%26%3D%2B%24%23
  • decodeURIComponent() 函数可对 encodeURIComponent() 函数编码的 URI 进行解码。
输入: 
<script type="text/javascript">

    var test1="http://www.w3school.com.cn/My first/"

    document.write(encodeURIComponent(test1)+ "<br />")
    document.write(decodeURIComponent(test1))

</script>

输出结果:
·http%3A%2F%2Fwww.w3school.com.cn%2FMy%20first%2F
http://www.w3school.com.cn/My first/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值