Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

escape & encodeURI & encodeURIComponent #20

Open
rhymecoding opened this issue Aug 24, 2018 · 0 comments
Open

escape & encodeURI & encodeURIComponent #20

rhymecoding opened this issue Aug 24, 2018 · 0 comments
Labels

Comments

@rhymecoding
Copy link

rhymecoding commented Aug 24, 2018

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:[email protected]:80/path/to/file-name.php?foo=316&zh=贺礼&bar=this+has+spaces#anchor'));
console.log(encodeURI('http://username:[email protected]:80/path/to/file-name.php?foo=316&zh=贺礼&bar=this+has+spaces#anchor'));
console.log(encodeURIComponent('http://username:[email protected]:80/path/to/file-name.php?foo=316&zh=贺礼&bar=this+has+spaces#anchor'));

// http%3A//username%[email protected]%3A80/path/to/file-name.php%3Ffoo%3D316%26zh%3D%u8D3A%u793C%26bar%3Dthis+has+spaces%23anchor
// http://username:[email protected]: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 ,所以不能重复编码。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants