您的位置:首页 > Web前端 > JavaScript

JS中的三种编码encodeUR、encodeURIComponent、escape()

2016-04-12 00:00 519 查看
摘要: JS中的三种编码encodeUR、encodeURIComponent、escape() 的区别和使用场合

一、encodeURI(str)和ecodeURIComponent(str)

都是把字符串作为参数,并对其进行编码,一般传入的参数是URI;两种方法都不会对‍ASCII码字母、数字、特定标点符号- _ . ! ~ * ' ( ) 等等】‍进行编码,保持原形。

但是,encodeURI()不会对在 URI 中具有特殊含义的 ASCII 标点符号【如分隔符: , / ? : @ & 空格 = + $ # 等等】进行编码,还是保持原形;在 ecodeURIComponent(str)中 会对这些符号进行编码,编码成由一个或多个十六进制的转义序列表示。

测试代码:encodeURI(str)

document.write(encodeURI("http://www.yhpage.com")+ "<br />")
document.write(encodeURI("http://www.yhpage.com/My test/")+ "<br />")
document.write(encodeURI(",/?:@&=+$#-_.!~*'()"))

结果:

http://www.yhpage.com http://www.yhpage.com/My%20test/ ,/?:@&=+$#
-_.!~*'()

测试代码:ecodeURIComponent(str)

<script type="text/javascript">

document.write(encodeURIComponent("http://www.yhpage.com")+ "<br />")
document.write(encodeURIComponent("http://www.yhpage.com/My test/")+ "<br />")
document.write(encodeURIComponent(",/?:@&=+$#")+ "<br />")
document.write(encodeURIComponent("-_.!~*'()"))

</script>

结果:

http%3A%2F%2Fwww.yhpage.com
http%3A%2F%2Fwww.yhpage.com%2FMy%20test%2F
%2C%2F%3F%3A%40%26%3D%2B%24%23
-_.!~*'()


二、escape()

主要是对字符串进行编码,一般不指URI

三、使用场合

1、如果只是编码字符串,和URL没关系,用escape

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

3、当只需要编码URL中的参数时,用encodeURIComponent
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息