您好,欢迎来到爱问旅游网。
搜索
您的当前位置:首页JS 转码 escape、encodeURI 、encodeURIComponent

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/

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- awee.cn 版权所有 湘ICP备2023022495号-5

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务