ifeees / articles

“前端晚自修”公众号文章备份
3 stars 0 forks source link

escape & encodeURI & encodeURIComponent #20

Open rhymecoding opened 6 years ago

rhymecoding commented 6 years ago

escape

对字符串进行编码(转成十六进制的转义序列),当字符小于等于 0xFF 时,则用一个2位转义序列 %xx 表示,当字符大于 0xFF 时,则用4位转义序列 %uxxxx 表示,其中 +-*/@._ 不会被处理

console.log(escape('abc')); // abc
console.log(escape('äöü')); // %E4%F6%FC
console.log(escape('贺礼')); // %u8D3A%u793C

escape 已经从 Web 标准中删除,请使用 encodeURIencodeURIComponent 代替。

encodeURI

对 URI 进行编码(转成十六进制的转义序列),encodeURI 不会对 URI 中合法的字符进行编码,比如

保留字符     / : @ ? = & ; , + $
非转义的字符  - _ . ! ~ * ' ( )
数字符号     #

encodeURIComponent

对字符串进行编码(转成十六进制的转义序列),不会对以下字符进行编码,返回值可以作为 URI 中的参数值

非转义的字符  - _ . ! ~ * ' ( )

对比

console.log(escape('http://username:password@www.example.com:80/path/to/file-name.php?foo=316&zh=贺礼&bar=this+has+spaces#anchor'));
console.log(encodeURI('http://username:password@www.example.com:80/path/to/file-name.php?foo=316&zh=贺礼&bar=this+has+spaces#anchor'));
console.log(encodeURIComponent('http://username:password@www.example.com:80/path/to/file-name.php?foo=316&zh=贺礼&bar=this+has+spaces#anchor'));

// http%3A//username%3Apassword@www.example.com%3A80/path/to/file-name.php%3Ffoo%3D316%26zh%3D%u8D3A%u793C%26bar%3Dthis+has+spaces%23anchor
// http://username:password@www.example.com:80/path/to/file-name.php?foo=316&zh=%E8%B4%BA%E7%A4%BC&bar=this+has+spaces#anchor
// http%3A%2F%2Fusername%3Apassword%40www.example.com%3A80%2Fpath%2Fto%2Ffile-name.php%3Ffoo%3D316%26zh%3D%E8%B4%BA%E7%A4%BC%26bar%3Dthis%2Bhas%2Bspaces%23anchor

escape 编码后的 URI 不再是一个合法的 URI,且不编码 / ,所以也不能作为 URI 中的参数值。 encodeURI 编码后的 URI 是一个合法的 URI,不能作为 URI 中的参数值。 encodeURIComponent 编码后的 URI 不再是一个合法的 URI,可以作为 URI 中的参数值。

编码%

因为 % 会被编码成 %25 ,所以不能重复编码。