JS 中有三个能够对字符串编码的函数,分别是: escape,encodeURI,encodeURIComponentgit
一般用于对字符串编码,不适用于对 URL 编码github
除了 ASCII 字母、数字和特定的符号外,对传进来的字符串所有进行转义编码,所以若是想对 URL 编码,最好不要使用此方法。函数
escape 不会编码的字符有 69 个:* + - . / @ _ 0-9 a-z A-Z
编码
固然若是没有必要,不要使用 escape。url
encodeURI()
不会进行编码的字符有 82 个 : ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) # 0-9 a-z A-Z
code
使用encodeURI()
编码后的结果是除了空格以外的其余字符都原封不动,只有空格被替换成了%20
,encodeURI
主要用于直接赋值给地址栏。blog
encodeURIComponent
:不会进行编码的字符有 71 个:! ' ( ) * - . _ ~ 0-9 a-z A-Z
字符串
encodeURIComponent
比encodeURI
编码的范围更大,如encodeURIComponent
会把 http://
编码成 http%3A%2F%2F
而encodeURI
不解码维持http://
get
encodeURIComponent()
方法在编码单个 URIComponent(指请求参数)应当是最经常使用的,它能够将参数中的中文、特殊字符进行转义,而不会影响整个 URLit
escape
。(但它已经被废弃,尽可能避免使用,应用encodeURI
或 encodeURIComponent
)encodeURI
encodeURIComponent
是最好方法。encodeURI("https://github.com/Jacky-Summer/test params");
编码后变成
https://github.com/Jacky-Summer/test%20params
其中空格被编码成了%20
,而若是是用encodeURIComponent
https%3A%2F%2Fgithub.com%2FJacky-Summer%2Ftest%20params
连 /
都被编码了,整个 URL 已经无法用了。
当编码 URL 的特殊参数时:
// 参数的 / 是须要编码的,而若是是 encodeURI 编码则不编码 / 就会出问题 let param = "https://github.com/Jacky-Summer/"; param = encodeURIComponent(param); const url = "https://github.com?param=" + param; console.log(url) // "https://github.com?param=https%3A%2F%2Fgithub.com%2FJacky-Summer%2F"
参考:https://www.zhihu.com/questio...