JavaScript编码encode和decode escape和unescape

encodeURI() 函数可把字符串作为 URI 进行编码。

语法

encodeURI(URIstring)
参数描述
URIstring 必需。一个字符串,含有 URI 或其他要编码的文本。

返回值

URIstring 的副本,其中的某些字符将被十六进制的转义序列进行替换。

说明

该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 。

该方法的目的是对 URI 进行完整的编码,因此对以下在 URI 中具有特殊含义的 ASCII 标点符号,encodeURI() 函数是不会进行转义的:;/?:@&=+$,#

提示和注释

提示:如果 URI 组件中含有分隔符,比如 ? 和 #,则应当使用 encodeURIComponent() 方法分别对各组件进行编码

<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<script type="text/javascript">
//测试编码URI的函数
    var url="http://www.nframes.com.cn/index.html?search=m %^^$#e";
    var res=encodeURI(url);
    document.write(res);
    var res1=decodeURI(res);
    document.write('<br/>'+res1+'<br/>');
</script>
</body>
</html>

结果:

http://www.nframes.com.cn/index.html?search=m%20%25%5E%5E$#e
http://www.nframes.com.cn/index.html?search=m %^^$#e

JavaScript escape() 函数

定义和用法

escape() 函数可对字符串进行编码,这样就可以在所有的计算机上读取该字符串。

语法

escape(string)
参数描述
string 必需。要被转义或编码的字符串。

返回值

已编码的 string 的副本。其中某些字符被替换成了十六进制的转义序列。

说明

该方法不会对 ASCII 字母和数字进行编码,也不会对下面这些 ASCII 标点符号进行编码: * @ - _ + . / 。其他所有的字符都会被转义序列替换。

提示和注释

提示:可以使用 unescape() 对 escape() 编码的字符串进行解码。

注释:ECMAScript v3 反对使用该方法,应用使用 decodeURI() 和 decodeURIComponent() 替代它。

实例

在本例中,我们将使用 escape() 来编码字符串:

<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<script type="text/javascript">
//测试编码URI的函数
    var url="http://www.nframes.com.cn/index.html?search=m %^^$#e";
    var res=escape(url);
    document.write(res);
    var res1=unescape(res);
    document.write('<br/>'+res1+'<br/>');
</script>
</body>
</html>

输出:

http%3A//www.nframes.com.cn/index.html%3Fsearch%3Dm%20%25%5E%5E%24%23e
http://www.nframes.com.cn/index.html?search=m %^^$#e


原文地址:https://www.cnblogs.com/Yimi/p/6344597.html