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进行编码.
声明:本站所有文章,如无特殊说明或标注,均为网络收集发布。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。