最近做的项目中,在给客户端发送的数据中有一个值为 url 链接的字段。 因为这个 url 中包含了个 json 字段的查询,有双引号,所以前端得将数据经过编码,发给客户端才不会出错。然后发现自己突然对这个操作有点生疏,索性在这里就总结下 JavaScript 中的那些编码解码问题。
- let data = {
- something: 'something',
- url: 'http://server.com/page/index.html?type=1&to={"target":"product_detail","uid":123456}'
- };
类型 | 包含 |
---|---|
保留字符 | ; , / ? : @ & = + $ |
非转义的字符 | 字母 数字 - _ . ! ~ * ‘ ( ) |
数字符号 | # |
请注意,encodeURI 自身无法产生能适用于HTTP GET 或 POST 请求的URI,例如对于 XMLHTTPRequests, 因为 “&”, “+”, 和 “=” 不会被编码,然而在 GET 和 POST 请求中它们是特殊字符。然而encodeURIComponent这个方法会对这些字符编码。
- let str = 'https://example.com/关于我.html?type=about';
- let encodeStr = encodeURI(str);
- // https://example.com/关于我.html?type=about
- decodeURI(encodeStr);
- // https://example.com/关于我.html?type=about
类型 | 包含 |
---|---|
非转义的字符 | 字母 数字 - _ . ! ~ * ‘ ( ) |
- let str = 'https://example.com/关于我.html?type=about';
- let encodeStr = encodeURIComponent(str);
- // https://example.com/关于我.html?type=about
- decodeURIComponent(encodeStr);
- // https://example.com/关于我.html?type=about
虽然 escape() 函数也可以进行相关编码,但是这个 js 的全局函数已经从 web 标准中删除,不再建议使用。
在众多的 Web API 接口中,有一个 WindowBase64 接口 定义了两个分别用来进行编码和解码
的工具函数。
- base64
WindowBase64 并不是一个全局对象,没有直接访问 WindowBase64 接口的方式。不过 Window 以及 WorkerGlobalScope 等接口实现了该接口,你可以在它们身上访问到 WindowBase64 的方法。
如果想对一个 Unicode 字符串进行编码,可以使用 encodeURIComponent 先对其进行编码,然后再进行 base64 编码。
- let str = 'https://example.com/关于我.html?type=about';
- let encodeStr = encodeURIComponent(str);
- // https://example.com/关于我.html?type=about
- window.btoa(encodeStr);
- // aHR0cHMlM0ElMkYlMkZleGFtcGxlLmNvbSUyRiVFNSU4NSVCMyVFNCVCQSU4RSVFNiU4OCU5MS5odG1sJTNGdHlwZSUzRGFib3V0
- let str = 'hello world'; // ASCII 字符串
- let base64Str = window.btoa(str);
- // aGVsbG8gd29ybGQ=
- window.atob(base64Str);
- // hello world
来源: http://www.tuicool.com/articles/z6bQjqM