encodeURI 方法

1、基本介绍
  • encodeURI 方法用于对完整的 URI 进行编码
encodeURI(URI)
  • 但是,encodeURI 方法不会对以下字符进行编码
类型 说明
保留字符 :,/?:@&=+$
非转义的字符 字母数字-_.!~*'()
数字符号 #
2、演示
const value = "https://example.com/test?name=测试用户&age=20#section";

const result = encodeURI(value);

console.log(result);
# 输出结果

https://example.com/test?name=%E6%B5%8B%E8%AF%95%E7%94%A8%E6%88%B7&age=20#section

decodeURI 方法

1、基本介绍
  • decodeURI 方法用于对 encodeURI 方法编码后的 URI 进行解码
decodeURI(URI)
2、演示
const value = "https://example.com/test?name=%E6%B5%8B%E8%AF%95%E7%94%A8%E6%88%B7&age=20#section";

const result = decodeURI(value);

console.log(result);
# 输出结果

https://example.com/test?name=测试用户&age=20#section

encodeURIComponent 方法

1、基本介绍
  • encodeURIComponent 方法用于对 URI 的组成部分进行编码,相比于 encodeURI 方法,encodeURIComponent 方法会编码更多的字符
encodeURIComponent(URI)
  • 但是,encodeURIComponent 方法不会对以下字符进行编码
A-Z
a-z
0-9
- _ . ! ~ * ' ( )
2、演示
const param = "name=zs&age=20";
const url = "https://example.com/search?" + encodeURIComponent(param);

console.log(url);
# 输出结果

https://example.com/search?name%3Dzs%26age%3D20
const value = "a/b?c=d&e=f";
const result = encodeURIComponent(value);

console.log(result);
# 输出结果

a%2Fb%3Fc%3Dd%26e%3Df
const value = "一段文本";
const result = encodeURIComponent(value);

console.log(result);
# 输出结果

%E4%B8%80%E6%AE%B5%E6%96%87%E6%9C%AC

decodeURIComponent 方法

1、基本介绍
  • decodeURIComponent 方法用于对 encodeURIComponent 方法编码后的 URI 进行解码
decodeURIComponent(URI)
2、演示
const value = "https://example.com/search?name%3Dzs%26age%3D20";

const result = decodeURIComponent(value);

console.log(result);
# 输出结果

https://example.com/search?name=zs&age=20
const value = "a%2Fb%3Fc%3Dd%26e%3Df";

const result = decodeURIComponent(value);

console.log(result);
# 输出结果

a/b?c=d&e=f
const value = "%E4%B8%80%E6%AE%B5%E6%96%87%E6%9C%AC";

const result = decodeURIComponent(value);

console.log(result);
# 输出结果

一段文本
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐