encodeURI()和encodeURIComponent() 区别

Global对象的encodeURI()和encodeURIComponent()方法可以对URI进行编码。

 

encodeURI()

encodeURI()主要用于整个URI(http://www.w3school.com.cn),实例:

<html>
<body>

<script type="text/javascript">

document.write(encodeURI("http://www.w3school.com.cn")+ "<br />")
document.write(encodeURI("http://www.w3school.com.cn/My first/")+ "<br />")
document.write(encodeURI(",/?:@&=+$#"))

</script>

</body>
</html>

运行结果为:

http://www.w3school.com.cn
http://www.w3school.com.cn/My%20first/
,/?:@&=+$#

 

encodeURIComponent()

encodeURIComponent()主要用于对URI中的某一段进行编码。它们的主要区别在于,encodeURI()不会对本身属于URI的特殊字符进行编码,例如冒号、正斜杠、问号和井字号;而encodeURIComponent()则会对它发现的任何非标准字符进行编码。来看下面的例子:

<html>
<body>

<script type="text/javascript">

document.write(encodeURIComponent("http://www.w3school.com.cn")+ "<br />")
document.write(encodeURIComponent("http://www.w3school.com.cn/My first/")+ "<br />")
document.write(encodeURIComponent(",/?:@&=+$#"))

</script>

</body>
</html>

运行结果为:

http%3A%2F%2Fwww.w3school.com.cn
http%3A%2F%2Fwww.w3school.com.cn%2FMy%20first%2F
%2C%2F%3F%3A%40%26%3D%2B%24%23

 

使用encodeURI()编码后的结果是除了空格之外的其他字符都原封不动,只有空格被替换成了%20。而encodeURIComponent()方法则会使用对应的编码替换所有非字母数字字符。这也正是可以对整个URI使用encodeURI(),而只能对附加在现有URI后面的字符串使用encodeURIComponent()的原因所在。一般来说,我们使用encodeURIComponent()方法的时候要比使用encodeURI()更多,因为在实践中更常见的是对查询字符串参数而不是对基础URL进行编码.

 

解码方法:decodeURI() 

               decodeURIComponent()

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值