• JS-编码函数:escape(),encodeURI(),encodeURIComponent()


    1、escape()

    escape()是js编码函数中最古老的一个。虽然这个函数现在已经不提倡使用了,但是由于历史原因,很多地方还在使用它,所以有必要先从它讲起。

    实际上,escape()不能直接用于URL编码,它的真正作用是返回一个字符的Unicode编码值。比如“春节”的返回结果是%u6625%u8282,也就是说在Unicode字符集中,“春”是第6625个(十六进制)字符,“节”是第8282个(十六进制)字符。

     escape("u6625u8282"); //输出 "%u6625%u8282"
    
     unescape("%u6625%u8282"); //输出 "春节"

    escape不编码字符有69个:*,+,-,.,/,@,_,0-9,a-z,A-Z。

    2、encodeURI()

    它于对整个URL进行编码,因此除了常见的符号以外,对其他一些在网址中有特殊含义的符号“; / ? : @ & = + $ , #”,也不进行编码。编码后,它输出符号的utf-8形式,并且在每个字节前加上%。

    encodeURI("http://www.cnblogs.com/fydxx/some other thing"); //=> "http://www.cnblogs.com/season-huang/some%20other%20thing";

    它对应的解码函数是decodeURI()。

    3、encodeURIComponent()

    最后一个Javascript编码函数是encodeURIComponent()。与encodeURI()的区别是,它用于对URL的组成部分进行个别编码,而不用于对整个URL进行编码。

    因此,“; / ? : @ & = + $ , #”,这些在encodeURI()中不被编码的符号,在encodeURIComponent()中统统会被编码。至于具体的编码方法,两者是一样。

    encodeURIComponent("http://www.cnblogs.com/fydxx/some other thing"); //=> http%3A%2F%2Fwww.cnblogs.com%2Fseason-huang%2Fsome%20other%20thing

    它对应的解码函数是decodeURIComponent()。

    总结:

    1、如果只是编码字符串,不和URL有半毛钱关系,那么用escape。

    2、如果你需要编码整个URL,然后需要使用这个URL,那么用encodeURI。

    3、当你需要编码URL中的参数的时候,那么encodeURIComponent是最好方法。

    附:

    escape不编码字符有69个:*,+,-,.,/,@,_,0-9,a-z,A-Z

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

    encodeURIComponent不编码字符有71个:!, ',(,),*,-,.,_,~,0-9,a-z,A-Z

  • 相关阅读:
    Hadoop配置文件参数详解
    Flume
    Oozie
    springmvc全局异常处理ControllerAdvice区分返回响应类型是页面还是JSON
    jsplumb 初识
    RabbitMQ 在Windows环境下安装
    Springboot2+SpringSecurity+Oauth2+Mysql数据库实现持久化客户端数据
    FastDFS与hadoop的HDFS区别
    springboot指定注解扫描范围
    Spring Boot2.0以上版本EmbeddedServletContainerCustomizer被WebServerFactoryCustomizer替代
  • 原文地址:https://www.cnblogs.com/fydxx/p/6673549.html
Copyright © 2020-2023  润新知