JS基本语法-JavaScript中的常用函数4:encodeURI() ,decodeURI(),encodeURIComponent(),decodeURIComponent()等编码和解码URI

1. 简介:

我们经常需要对URI进行编码和解码,在JavaScript中,提供了encodeURI() ,decodeURI(),encodeURIComponent(),decodeURIComponent()等编码和解码URI的内部函数。

URI,统一资源标志符(Uniform Resource Identifier, URI),表示的是web上每一种可用的资源,如 HTML文档、图像、视频片段、程序等都由一个URI进行标识的。

2. encodeURI() 和decodeURI()使用举例:

.encodeURI(uri):对参数uri进行编码,uri为字符串。

encodeURI()函数只对字符串中有意义的字符进行转义。例如将字符串中的空格转化为“%20”。

.decodeURI(uri):解码已经编码的字符串。

decodeURI()是encodeURI()函数的逆向操作。

代码举例:

encode.js:

function endecode_test(){
	var uri = "http://127.0.0.1/test.html?name=张三&age=30";
	var encodeResStr =  encodeURI(uri);
    console.log(encodeResStr); 
    console.log(decodeURI(encodeResStr)); 
}

encode.html:

<!DOCTYPE html>
<html>
<body>
<script src="./encode.js"></script>

<h1>JavaScript中的常用函数4:编码URI和解码URI</h1>
<p id="res">结果:</p>
<script>
	endecode_test();
</script>

</body>
</html>

运行结果:

在控制台可以看到:

encodeRes = http://127.0.0.1/test.html?name=%E5%BC%A0%E4%B8%89&age=30
encode.js:5

decodeRes = http://127.0.0.1/test.html?name=张三&age=30

3. encodeURIComponent() 和decodeURIComponent()使用举例:

.encodeURIComponent(uri):字符串作为 URI 组件进行编码,uri为字符串。

encodeURIComponent()方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 。
所谓组件,通常会被如下符号分割的字符串::;/?:@&=+$,# 。

.decodeURIComponent(uri):解码已经编码的字符串,是encodeURIComponent()函数的逆向操作。

代码举例:

encode.js:


function endecodeURIComponent_test(){
	var uri = "http://127.0.0.1/test.html?name=张三&age=30";
	var encodeResStr =  encodeURIComponent(uri);
    console.log("encodeRes = " + encodeResStr); 
    console.log("decodeRes = " + decodeURIComponent(encodeResStr)); 
}

encode.html:

<!DOCTYPE html>
<html>
<body>
<script src="./encode.js"></script>

<h1>JavaScript中的常用函数4:编码URI和解码URI</h1>
<p id="res">结果:</p>
<script>
	endecodeURIComponent_test();
</script>

</body>
</html>

 

运行结果:

encodeRes = http%3A%2F%2F127.0.0.1%2Ftest.html%3Fname%3D%E5%BC%A0%E4%B8%89%26age%3D30
encode.js:12

decodeRes = http://127.0.0.1/test.html?name=张三&age=30

 说明:

encodeURIComponent()和encodeURI()的最主要区别是:前者对保留字符同样做转义编码,后者则不会。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

liranke

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

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

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

打赏作者

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

抵扣说明:

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

余额充值