zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    hdu 3333 树状数组+离线处理
    poj 2352 树状数组 OR Treap
    hdu 1698 线段树
    【概率dp】D. Card Collector
    【分段哈希】H. Paint the Wall
    【置换】G. Poker 2.0
    【概率dp】C. Race to 1 Again
    【dp】D. Caesar's Legions
    【并查集】F.find the most comfortable road
    【算法系列学习】连续邮资问题
  • 原文地址:https://www.cnblogs.com/fydxx/p/6673549.html
Copyright © 2011-2022 走看看