escape()、encodeURI()、encodeURIComponent()区别

本文详细介绍了 JavaScript 中用于 URL 编码和转义的三个函数:escape(), encodeURI(), encodeURIComponent() 的用法及区别。通过示例演示了如何对 URL 进行编码,并解释了它们在不同场景下的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 escape()

<script type="text/javascript">

document.write(escape("http://www.w3school.com.cn/") + "<br />")

document.write(escape("?!=()#%&"))

</script>输出:

http%3A//www.w3school.com.cn

%3F%21%3D%28%29%23%25%26

2 encodeURI()

<script type="text/javascript">

document.write(encodeURI("http://www.w3school.com.cn/")+ "<br />")

document.write(encodeURI("http://www.w3school.com.cn/My first/"))

document.write(encodeURI(",/?:@&=+$#"))

</script>输出:

http://www.w3school.com.cn/

http://www.w3school.com.cn/My%20first/

,/?:@&=+$#

对整个URL进行编码,而URL的特定标识符不会被转码。

3 encodeURIComponent()

例1:

<script type="text/javascript">

document.write(encodeURIComponent("http://www.w3school.com.cn/"))

document.write("<br />")

document.write(encodeURIComponent("http://www.w3school.com.cn/p 1/"))

document.write("<br />")

document.write(encodeURIComponent(",/?:@&=+$#"))

</script输出:

https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttp%2Fwww.w3school.com.cn 
https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttp%2Fwww.w3school.com.cn%2Fp%201%2F 
%2C%2F%3F%3A%40%26%3D%2B%24%23
例2:<script language="javascript">document.write('

<a href="http://passport.baidu.com/?logout&aid=7&u='+encodeURIComponent("http://cang.baidu.com/bruce42")+'">退出</a>');</script>

对URL中的参数进行编码,因为参数也是一个URL,如果不编码会影响整个URL的跳转。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值