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

JavaScript
一、encodeURI() 函数

在本例中,我们将使用 encodeURI() 对 URI 进行编码:

<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/
,/?:@&=+$#
二、encodeURIComponent() 函数

在本例中,我们将使用 encodeURIComponent() 对 URI 进行编码:

<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>

输出:

http%3A%2F%2Fwww.w3school.com.cn
http%3A%2F%2Fwww.w3school.com.cn%2Fp%201%2F
%2C%2F%3F%3A%40%26%3D%2B%24%23
三、escape() 函数

在本例中,我们将使用 escape() 来编码字符串:

<script type="text/javascript">

document.write(escape("Visit W3School!") + "<br />")
document.write(escape("?!=()#%&"))

</script>

输出:

Visit%20W3School%21
%3F%21%3D%28%29%23%25%26
四、总结

通过对三个函数的分析,我们可以知道:escape()除了 ASCII 字母、数字和特定的符号外,对传进来的字符串全部进行转义编码,因此如果想对URL编码,最好不要使用此方法。而encodeURI() 用于编码整个URI,因为URI中的合法字符都不会被编码转换。encodeURIComponent方法在编码单个URIComponent(指请求参 数)应当是最常用的,它可以讲参数中的中文、特殊字符进行转义,而不会影响整个URL。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容