`
lmh2072005
  • 浏览: 111371 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

javascript中的编码和解码

    博客分类:
  • js
阅读更多

1. encodeURIComponent(url) 函数可把字符串作为 URI 组件进行编码。

 

该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 。

其他字符(比如 :;/?:@&=+$,# 这些用于分隔 URI 组件的标点符号),都是由一个或多个十六进制的转义序列替换的。

encodeURIComponent() 函数将转义用于分隔 URI 各个部分的标点符号。

 

eg:


 

document.write(encodeURIComponent("http://www.w3school.com.cn/p 1/"))

 

 

输出:http%3A%2F%2Fwww.w3school.com.cn%2Fp%201%2F

 

 

 

document.write(encodeURIComponent(",/?:@&=+$#"))

 

输出:%2C%2F%3F%3A%40%26%3D%2B%24%23

 

 

 

 

2. encodeURI(url) 函数可把字符串作为 URI 进行编码。

 

 该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 。

 

该方法的目的是对 URI 进行完整的编码,因此对以下在 URI 中具有特殊含义的 ASCII 标点符号,encodeURI() 函数是不会进行转义的:;/?:@&=+$,#

如果 URI 组件中含有分隔符,比如 ? 和 #,则应当使用 encodeURIComponent() 方法分别对各组件进行编码。

 

 

eg:

 

document.write(encodeURI("http://www.w3school.com.cn/My first/"))

 

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

 

document.write(encodeURI(",/?:@&=+$#"))

 

输出:,/?:@&=+$#

 

 

 

 

3. decodeURIComponent(url) 函数可对 encodeURIComponent() 函数编码的 URI 进行解码。

 

eg:

 

var test1="http://www.w3school.com.cn/My first/"
document.write(encodeURIComponent(test1)+ "<br />")
document.write(decodeURIComponent(test1))

 

输出:http%3A%2F%2Fwww.w3school.com.cn%2FMy%20first%2F
     http://www.w3school.com.cn/My first/

 

 

 

 

4. decodeURI(url) 函数可对 encodeURI() 函数编码过的 URI 进行解码。

 

eg:

 

var test1="http://www.w3school.com.cn/My first/"
document.write(encodeURI(test1)+ "<br />")
document.write(decodeURI(test1))

 

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

 

 

 

 

5. escape() 函数可对字符串进行编码

   该方法不会对 ASCII 字母和数字进行编码,也不会对下面这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 。其他所有的字符都会被转义序列替换。

  可以使用 unescape() 对 escape() 编码的字符串进行解码。

  ECMAScript v3 反对使用该方法,应用使用 decodeURI() 和 decodeURIComponent() 替代它。

 

 eg:

 

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

 

输出:Visit%20W3School%21
     %3F%21%3D%28%29%23%25%26

 

 

 

6. unescape() 函数可对通过 escape() 编码的字符串进行解码。

    该函数的工作原理是这样的:通过找到形式为 %xx 和 %uxxxx 的字符序列(x 表示十六进制的数字),用 Unicode 字符 \u00xx 和 \uxxxx 替换这样的字符序列进行解码。

    ECMAScript v3 已从标准中删除了 unescape() 函数,并反对使用它,因此应该用 decodeURI() 和 decodeURIComponent() 取而代之。

 

eg:

 

var test1="Visit W3School!"
test1=escape(test1)
document.write (test1 + "<br />")
test1=unescape(test1)
document.write(test1 + "<br />")
输出:Visit%20W3School%21     
     Visit W3School!

 

网上看到不用后两个编码解码方法可能是 escape() 只是为 ASCII字符 做转换工作,转换成的 %unnnn 这样的码,如果要用更多的字符如 UTF-8字符库 就一定要用 encodeURIComponent() 或 encodeURI() 转换才可以成 %nn%nn 这的码才可以

 

以上内容参考http://www.w3school.com.cn/  和网上记录下

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics