首页 > 编程语言 > 详细

JavaScript编码encode和decode escape和unescape

时间:2017-01-23 19:08:28      阅读:182      评论:0      收藏:0      [点我收藏+]

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

 



JavaScript编码encode和decode escape和unescape

原文:http://www.cnblogs.com/Yimi/p/6344597.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!