js的编码和解码

本文详细介绍了JavaScript中的编码和解码函数,包括encodeURIComponent()、decodeURIComponent()以及encodeURI(),展示了它们在处理URI组件和特殊字符时的不同作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在 JavaScript 中,可以使用以下内置函数来进行编码和解码:

编码

  • encodeURIComponent(): 该函数用于对 URI 组件进行编码,它可以将字符串中的特殊字符转换为对应的编码形式。例如,空格会被编码为 %20
var originalString = "Hello World!";
var encodedString = encodeURIComponent(originalString);
console.log(encodedString); // 输出 "Hello%20World%21"
  • encodeURI(): 该函数用于对整个 URI 进行编码,它与 encodeURIComponent() 函数的区别在于不会对某些特殊字符进行编码,如 :/? 等。
var originalURL = "http://example.com/path?query=hello world";
var encodedURL = encodeURI(originalURL);
console.log(encodedURL); // 输出 "http://example.com/path?query=hello%20world"

解码 

  • decodeURIComponent(): 该函数用于对通过 encodeURIComponent() 函数编码的字符串进行解码,将编码后的字符串转换为原始字符。
    var encodedString = "Hello%20World%21";
    var decodedString = decodeURIComponent(encodedString);
    console.log(decodedString); // 输出 "Hello World!"
    
  • decodeURI(): 该函数用于对通过 encodeURI() 函数编码的 URI 进行解码,还原原始的 URI。
var encodedURL = "http://example.com/path?query=hello%20world";
var decodedURL = decodeURI(encodedURL);
console.log(decodedURL); // 输出 "http://example.com/path?query=hello world"

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

娃哈哈哈哈呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值