escape、encodeURI和encodeURIComponent

escape:可对字符串进行编码,不会对 ASCII 字母和数字进行编码,也不会对下面这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 。其他所有的字符都会被转义序列替换。


encodeURI:可把字符串作为URI进行编码,encodeURI方法不会对下列字符进行编码:":"、"/"、";" 和 "?"等特殊字符

js:

var name1=document.getElementById("key").value;

var name=encodeURI(name);

window.location.href="a.jsp?name="+name;

java:

String name1 = request.getParameter("name");

String name = name1.getBytes("ISO-8859-1","UTF-8");


encodeURIComponent:可把字符串作为URI组件进行编码

js:

var name1 = document.getElementById("key").value;

var name = encodeURIComponent(encodeURIComponent(name1)); 

java:

String name1 = request.getParameter("name");

String name = URLDecorder.decode(name1,"UTF-8");


例子:(转载)

1 escape()

<script type="text/javascript">
document.write(escape("http://www.w3school.com.cn") + "<br />")
document.write(escape("?!=()#%&"))
</script>

输出:

http%3A//www.w3school.com.cn
%3F%21%3D%28%29%23%25%26
 

2 encodeURI()

<script type="text/javascript">
document.write(encodeURI("http://www.w3school.com.cn")+ "<br />")
document.write(encodeURI("http://www.w3school.com.cn/My first/"))
document.write(encodeURI(",/?:@&=+$#"))
</script>

输出:

http://www.w3school.com.cn
http://www.w3school.com.cn/My%20first/
,/?:@&=+$#

对整个URL进行编码,而URL的特定标识符不会被转码。

3 encodeURIComponent()
<script type="text/javascript">
document.write(encodeURIComponent("http://www.w3school.com.cn"))
document.write("<br />")
document.write(encodeURIComponent("http://www.w3school.com.cn/p 1/"))
document.write("<br />")
document.write(encodeURIComponent(",/?:@&=+$#"))
</script>

输出:

http%3A%2F%2Fwww.w3school.com.cn
http%3A%2F%2Fwww.w3school.com.cn%2Fp%201%2F
%2C%2F%3F%3A%40%26%3D%2B%24%23



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值