温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》
  • 首页 > 
  • 教程 > 
  • 开发技术 > 
  • js之encodeURI、encodeURIComponent、decodeURI、decodeURIComponent怎么用

js之encodeURI、encodeURIComponent、decodeURI、decodeURIComponent怎么用

发布时间:2023-04-17 10:01:55 来源:亿速云 阅读:413 作者:iii 栏目:开发技术

js之encodeURI、encodeURIComponent、decodeURI、decodeURIComponent怎么用

在JavaScript中,处理URL编码和解码是非常常见的操作。为了确保URL中的特殊字符能够正确传输和解析,JavaScript提供了四个主要的函数:encodeURIencodeURIComponentdecodeURIdecodeURIComponent。本文将详细介绍这些函数的用法和区别。

1. encodeURI

encodeURI 函数用于对整个URI进行编码。它会将URI中的特殊字符(如空格、中文等)转换为UTF-8编码的字符序列,但不会对URI中的保留字符(如:/?#[]@!$&'()*+,;=)进行编码。

使用场景

  • 当你需要对整个URL进行编码时,可以使用encodeURI

示例

const url = "https://example.com/路径/文件.html?name=张三&age=20";
const encodedUrl = encodeURI(url);
console.log(encodedUrl);
// 输出: "https://example.com/%E8%B7%AF%E5%BE%84/%E6%96%87%E4%BB%B6.html?name=%E5%BC%A0%E4%B8%89&age=20"

2. encodeURIComponent

encodeURIComponent 函数用于对URI的组成部分进行编码。与encodeURI不同,encodeURIComponent会对所有非字母数字字符进行编码,包括保留字符。

使用场景

  • 当你需要对URL中的查询参数或路径部分进行编码时,可以使用encodeURIComponent

示例

const param = "name=张三&age=20";
const encodedParam = encodeURIComponent(param);
console.log(encodedParam);
// 输出: "name%3D%E5%BC%A0%E4%B8%89%26age%3D20"

3. decodeURI

decodeURI 函数用于解码由encodeURI编码的URI。它会将编码后的字符序列转换回原始字符。

使用场景

  • 当你需要解码整个URL时,可以使用decodeURI

示例

const encodedUrl = "https://example.com/%E8%B7%AF%E5%BE%84/%E6%96%87%E4%BB%B6.html?name=%E5%BC%A0%E4%B8%89&age=20";
const decodedUrl = decodeURI(encodedUrl);
console.log(decodedUrl);
// 输出: "https://example.com/路径/文件.html?name=张三&age=20"

4. decodeURIComponent

decodeURIComponent 函数用于解码由encodeURIComponent编码的URI组成部分。它会将编码后的字符序列转换回原始字符。

使用场景

  • 当你需要解码URL中的查询参数或路径部分时,可以使用decodeURIComponent

示例

const encodedParam = "name%3D%E5%BC%A0%E4%B8%89%26age%3D20";
const decodedParam = decodeURIComponent(encodedParam);
console.log(decodedParam);
// 输出: "name=张三&age=20"

总结

  • encodeURIdecodeURI 用于对整个URI进行编码和解码,保留URI中的保留字符。
  • encodeURIComponentdecodeURIComponent 用于对URI的组成部分进行编码和解码,编码所有非字母数字字符。

在实际开发中,根据具体需求选择合适的编码和解码函数,可以确保URL的正确传输和解析。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI