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



發佈了37 篇原創文章 · 獲贊 10 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章