JavaScript中的编码函数

编码函数有三个:

escape、encodeURI、encodeURIComponent

主要区别:

非URI编码 :escape仅对String对象编码,不能用来对统一资源标示码URI进行编码

URI编码 :encodeURI、encodeURIComponent

encodeURI 与 encodeURIComponent 的区别

encodeURI 方法返回一个编码的 URI,encodeURI 方法不会对下列字符进行编码:":"、"/"、";" 和 "?"。如果需要对这些进行编码则需要使用encodeURIComponent方法

encodeURIComponent 方法对所有的字符编码,如果该字符串代表一个路径,例如 /folder1/folder2/default.html,其中的斜杠也将被编码。当该编码结果被作为请求发送到 web 服务器时将是无效的,如果字符串中包含不止一个 URI 组件,请使用 encodeURI 方法进行编码。

使用encodeURIComponent 对一个url地址转码得到如下的编码后的字符串:

image

需要得到路径的不要使用encodeURIComponent ,建议使用encodeURI

如遇到特殊的需求,需要将:":"、"/"、";" 和 "?"进行编码的,就使用encodeURIComponent

原文地址:https://www.cnblogs.com/meteoric_cry/p/1828043.html