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进行编码.
热门文章
- 11月23日 - 最高速度21.7M/S,2024年Surfboard每天更新免费节点订阅链接,干净IP机场推荐
- 11月27日 - 最高速度22.7M/S,2024年Surfboard每天更新免费节点订阅链接,干净IP机场推荐
- 猫三联每一针间隔时间多久(猫三联一针多少)
- 12月17日 - 最高速度21.4M/S,2024年Surfboard每天更新免费节点订阅链接,干净IP机场推荐
- 实现垂直居中的几种方式
- 12月2日 - 最高速度22.1M/S,2024年Surfboard每天更新免费节点订阅链接,干净IP机场推荐
- 1月1日 - 最高速度19M/S,2025年Surfboard每天更新免费节点订阅链接,干净IP机场推荐
- 12月26日 - 最高速度18.8M/S,2024年Surfboard每天更新免费节点订阅链接,干净IP机场推荐
- ASP.NET Core使用EF保存数据、级联删除和事务使用_实用技巧
- 11月20日 - 最高速度21.1M/S,2024年Surfboard每天更新免费节点订阅链接,干净IP机场推荐