对URL字符串进行编码和解码,全面支持encodeURIComponent和decodeURIComponent方法
| 字符 | 编码后 | 说明 | 组件安全 |
|---|---|---|---|
! |
%21 | 感叹号 | ✗ |
# |
%23 | 井号 | ✗ |
$ |
%24 | 美元符号 | ✗ |
& |
%26 | 和号 | ✗ |
+ |
%2B | 加号 | ✗ |
, |
%2C | 逗号 | ✗ |
/ |
%2F | 斜杠 | ✓ |
: |
%3A | 冒号 | ✓ |
; |
%3B | 分号 | ✗ |
= |
%3D | 等号 | ✗ |
@ |
%40 | @符号 | ✓ |
space |
%20 | 空格 | ✗ |
? |
%3F | 问号 | ✗ |
[ ] |
%5B %5D | 方括号 | ✗ |
💡 提示:编码查询参数值时使用组件编码(encodeURIComponent);编码完整URL路径时使用完整URL编码(encodeURI)。
URL编码(百分号编码)是互联网基础编码方式,将URL中的特殊字符转换为%加两位十六进制数。空格变为%20,中文变为UTF-8字节序列的百分号编码。HTTP协议规定URL只能使用ASCII字符,非ASCII和保留字符必须编码。
JavaScript提供encodeURI()(不编码URL保留字符)和encodeURIComponent()(编码所有特殊字符)。
console.log(encodeURI("https://example.com/path?name=hello world"));
console.log(encodeURIComponent("hello world"));
const params = new URLSearchParams({q:"hello"});
console.log(params.toString());
Q:encodeURI和encodeURIComponent区别?
前者不编码URL保留字符,后者编码所有非字母数字。