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




转载于:https://my.oschina.net/summeryh/blog/657172

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值