本篇文章给大家带来的内容是关于javascript如何实现url的转码与解码?有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
1. escape 和 unescape
escape()不能直接用于url编码,它的真正作用是返回一个字符的unicode编码值。
采用unicode字符集对指定的字符串除0-255以外进行编码。所有的空格符、标点符号、特殊字符以及更多有联系非ascii字符都将被转化成%xx格式的字符编码(xx等于该字符在字符集表里面的编码的16进制数字)。比如,空格符对应的编码是%20。
escape不编码字符有69个:*,+,-,.,/,@,_,0-9,a-z,a-z。
escape()函数用于js对字符串进行编码,不常用。
编码:
escape('http://www.baidu.com?name=zhang@xiao@jie&order=1')
结果:"http%3a//www.baidu.com%3fname%3dzhang@xiao@jie%26order%3d1"
escape('张')
结果:"%u5f20"
解码:
unescape("http%3a//www.baidu.com%3fname%3dzhang@xiao@jie%26order%3d1")
结果:"http://www.baidu.com?name=zhang@xiao@jie&order=1"
unescape("%u5f20")
结果:"张"
2. encodeuri 和 decodeuri
把uri字符串采用utf-8编码格式转化成escape各式的字符串。
encodeuri不编码字符有82个:!,#,$,&,',(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a-z,a-z
encodeuri()用于整个url编码
编码:
encodeuri('http://www.baidu.com?name=zhang@xiao@jie&order=1')
结果:"http://www.baidu.com?name=zhang@xiao@jie&order=1"
解码:
decodeuri("http%3a//www.baidu.com%3fname%3dzhang@xiao@jie%26order%3d1")
结果:"http%3a//www.baidu.com%3fname%3dzhang@xiao@jie%26order%3d1"
3. encodeuricomponent 和 decodeuricomponent
与encodeuri()的区别是,它用于对url的组成部分进行个别编码,而不用于对整个url进行编码。
因此,"; / ? : @ & = + $ , #",这些在encodeuri()中不被编码的符号,在encodeuricomponent()中统统会被编码。至于具体的编码方法,两者是一样。把uri字符串采用utf-8编码格式转化成escape格式的字符串。
encodeuricomponent() 用于参数的传递,参数包含特殊字符可能会造成间断。
编码:
encodeuricomponent('http://www.baidu.com?name=zhang@xiao@jie&order=1')
结果:"http%3a%2f%2fwww.baidu.com%3fname%3dzhang%40xiao%40jie%26order%3d1"
解码:
decodeuricomponent("http%3a%2f%2fwww.baidu.com%3fname%3dzhang%40xiao%40jie%26order%3d1")
结果:http://www.baidu.com?name=zhang@xiao@jie&order=1
总结:
escape()不能直接用于url编码,它的真正作用是返回一个字符的unicode编码值。比如春节的返回结果是%u6625%u8282,,escape()不对+编码
主要用于汉字编码,现在已经不提倡使用。
encodeuri()是javascript中真正用来对url编码的函数。
编码整个url地址,但对特殊含义的符号; / ? : @ & = + $ , #,也不进行编码。对应的解码函数是:decodeuri()。
encodeuricomponent()
能编码; / ? : @ & = + $ , #这些特殊字符。对应的解码函数是decodeuricomponent()。
我想要传递带&符号的网址,所以用encodeuricomponent()
以上就是javascript如何实现url的转码与解码?的详细内容。