黑铁时代
Programing is not only one kind of technology, but also one kind of art.

encodeURI 和 encodeURIComponent 两个方法都是用来对URI(统一资源标志符)进行编码的,他们会用UTF-8编码替换URI中无效的字符。编码的目的是因为浏览器不会接受一些非法的字符作为URI,比如空格。

 

区别:encodeURI 用于编码整个URI,因为它不会编码URI中那些标准的字符,比如/,:?,#;而 encodeURIComponent 会对所有非字母和数字的字符进行编码。

 

例子:

var uri = "http://www.leo.com/getUser?userid=123#username=leo wu";

 

console.log(encodeURI(uri));

// 输出 http://www.leo.com/getUser?userid=123#username=leo%20wu, 只对其中的空格进行了编码,空格编码成了%20


console.log(encodeURIComponent(uri));

// 输出 http%3A%2F%2Fwww.leo.com%2FgetUser%3Fuserid%3D123%23username%3Dleo%20wu,对其中所以非数字字母的字符进行了编码,/编码成了%2F,#编码成了%23

 

当然对应了还有两个解码的方法:decodeURI 和 decodeURIComponent。decodeURI同样不会解析编码后的 /,:?,#,而 decodeURIComponent 会解析所有的被编码的字符。

posted on 2012-06-30 17:31  黑铁时代  阅读(140)  评论(0编辑  收藏  举报