# encodeURI编码

用于编码统一资源标识符(URI),有效的URI不包括某些字符如空格等,使用这encodeURI,encodeURIComponent可帮助浏览器理解。

# encodeURIComponent编码

encodeURIComponent()是对统一资源标识符(URI)的组成部分进行编码的方法。它使用一到四个转义序列来表示字符串中的每个字符的UTF-8编码(只有由两个Unicode代理区字符组成的字符才用四个转义字符编码)。encodeURIComponent 转义除了字母、数字、(、)、.、!、~、*、'、-和_之外的所有字符。

二者区别:encodeURI不会编码属于URL的特殊字符如冒号,斜杠,问号,井号

let uri = "http:// www.wrox.com/illegal value.js#start";
         
// "http:// www.wrox.com/illegal%20value.js#start"
console.log(encodeURI(uri));
         
// "http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.js%23start"
console.log(encodeURIComponent(uri));

# decodeURI 解码

解码encodeURI编码的内容.

# decodeURIComponent

解码 encodeURIComponent编码的内容.

let uri = "http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.js%23start";
         
// http%3A%2F%2Fwww.wrox.com%2Fillegal value.js%23start
console.log(decodeURI(uri));
         
// http:// www.wrox.com/illegal value.js#start
console.log(decodeURIComponent(uri));

总结

  • encodeURIComponent使用频率高于encodeURI
  • escape()和unescape()已被废弃,不要在生产环境使用
最后更新: 12/14/2021, 10:03:18 AM