encodeURI、encodeURIComponent、decodeURI、decodeURIComponent 的区别

这些函数都是 JavaScript 中用于 URI(统一资源标识符)编码和解码的方法。它们的作用是在 URL 中对特定字符进行转义或解码,以确保它们在传输过程中不会被误解或丢失。

以下是它们之间的区别:

  1. encodeURI

    • encodeURI 用于对整个 URI 进行编码,包括协议、域名、路径和查询参数等。
    • 不会对特殊字符 ; , / ? : @ & = + $ # 进行编码,以保留其在 URI 中的含义。
    • 只会对其他非 ASCII 字符(Unicode 字符)进行编码。
  2. encodeURIComponent

    • encodeURIComponent 用于对 URI 中的查询参数进行编码。
    • 会对除了字母、数字和特殊字符 - _ . ! ~ * ' ( ) 之外的所有字符进行编码。
  3. decodeURI

    • decodeURI 用于对整个 URI 进行解码,与 encodeURI 对应。
    • 对使用 encodeURI 编码的所有字符进行解码,包括非 ASCII 字符。
  4. decodeURIComponent

    • decodeURIComponent 用于对 URI 中的查询参数进行解码,与 encodeURIComponent 对应。
    • 对使用 encodeURIComponent 编码的所有字符进行解码,包括特殊字符。

使用示例:

const uri = 'https://example.com/path/to/file.html?key=value&name=John Doe';

const encodedURI = encodeURI(uri);
console.log(encodedURI);
// 输出:https://example.com/path/to/file.html?key=value&name=John%20Doe

const encodedComponent = encodeURIComponent(uri);
console.log(encodedComponent);
// 输出:https%3A%2F%2Fexample.com%2Fpath%2Fto%2Ffile.html%3Fkey%3Dvalue%26name%3DJohn%20Doe

const decodedURI = decodeURI(encodedURI);
console.log(decodedURI);
// 输出:https://example.com/path/to/file.html?key=value&name=John Doe

const decodedComponent = decodeURIComponent(encodedComponent);
console.log(decodedComponent);
// 输出:https://example.com/path/to/file.html?key=value&name=John Doe

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值