看懂encodeURI、encodeURIComponent、decodeURI、decodeURIComponent的区别

本文详细介绍了JavaScript中用于处理URI的四种方法:encodeURI、decodeURI、encodeURIComponent、decodeURIComponent的功能与区别,以及escape和unescape函数的使用场景,帮助读者理解如何正确地对URI进行编码和解码。

一、这四个方法的用处

1、用来编码和解码URI的

encodeURI()  //转义一个URI中的字符

语法:encodeURI(uri)  //这个在编码不同的AJAX请求时,解决中文乱码问题经常用到。

var str1 = "aerchi, hello world. /";
var str2 = encodeURI(str1);
document.write(str2);   //aerchi,%20hello%20world.%20/ 

decodeURI()  //解码一个URI中的字符

语法:decodeURI(uri)

var str1 = "aerchi, hello world. /";
var str2 = encodeURI(str1);
document.write(str2);   //aerchi,%20hello%20world.%20/ 

var str3 = decodeURI(str2);
document.write("<br/>" + str3)  //aerchi, hello world. /

encodeURIComponent()  //转义URI组件中的字符

var str1 = "aerchi, hello world. /";
var str2 = encodeURIComponent(str1);
document.write(str2);   //aerchi%2C%20hello%20world.%20%2F

decodeURIComponent()  //解码一个URI组件中的字符

var str1 = "aerchi, hello world. /";
var str2 = encodeURIComponent(str1);
document.write(str2);   //aerchi%2C%20hello%20world.%20%2F
var str3 = decodeURIComponent(str2);
document.write("<br/>" + str3)  //aerchi, hello world. 

escape()  //编码一个字符串

语法:escape(value);

var str = "aerchi, hello world. /";
var str1 = escape(str);
document.write(str1);  //aerchi%2C%20hello%20world.%20/

 

unescape()  //解码一个由escape()函数编码的字符串

window.onload = function () {
    var str = "aerchi, hello world. /";
    var str1 = escape(str);
    document.write(str1); //aerchi%2C%20hello%20world.%20/

    var str2 = unescape(str1);
    alert(str2);      //弹出: aerchi, hello world. /
}

2、有和不同?

encodeURI 和 decodeURI 函数操作的是完整的 URI;这俩函数假定 URI 中的任何保留字符都有特殊意义,所有不会编码它们。

 

encodeURIComponent 和 decodeURIComponent 函数操作的是组成 URI 的个别组件;这俩函数假定任何保留字符都代表普通文本,所以必须编码它们,所以它们(保留字符)出现在一个完整 URI 的组件里面时不会被解释成保留字符了。

escape和unescape用在浏览区地址栏不会自动解码

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值