首先,我們都知道這三個東西都是用來編碼的先來說encodeURI()和encodeURIComponent(),這兩個是在轉換url時候用來編碼解碼用的。
有編碼就會有解碼,解碼就是decodeURI()和decodeURIComponent(),他們的用法很簡單,在參數中帶入要轉碼的文字就可實現目的
如:
encodeURI("我是要編碼的文字")
decodeURI("我是要解碼的文字")
encodeURIComponent("我是要編碼的文字")
decodeURIComponent("我是要解碼的文字")
而encodeURI()和encodeURIComponent()的區別其實並不大
主要區別在於:
encodeURI不編碼字符有82個:!,#,$,&,',(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a-z,A-Z
encodeURIComponent不編碼字符有71個:!, ',(,),*,-,.,_,~,0-9,a-z,A-Z
encodeURI主要用於直接賦值給地址欄時候:
location.href=encodeURI("http://www.cnblogs.com/Tezml/");
而encodeURIComponent主要用於url的query參數:
location.href="http://www.cnblogs.com/Tezml/test.php?a="+encodeURIComponent("我就是我");
而escape,相比於上面那兩個,就有所不同了
escape()是編碼,unescape()是解碼;
escape 方法
對 String 對象編碼以便它們能在所有計算機上可讀,
escape(charString)
必選項 charstring 參數是要編碼的任意 String 對象或文字。
說明
escape 方法返回一個包含了 charstring 內容的字符串值( Unicode 格式)。所有空格、標點、重音符號以及其他非 ASCII 字符都用 %xx 編碼代替,
其中 xx 等於表示該字符的十六進制數。例如,空格返回的是 "%20" 。
字符值大於 255 的以 %uxxxx 格式存儲。
escape不編碼字符有69個:*,+,-,.,/,@,_,0-9,a-z,A-Z
注意 escape 方法不能夠用來對統一資源標示碼 (URI) 進行編碼。對其編碼應使用 encodeURI 和encodeURIComponent 方法。
最後上一段關於編碼解碼的demo
<!DOCTYPE html>
<html>
<head>
<title>Tezml_編碼解碼測試</title>
<meta charset="utf-8">
<meta name="author" content="Tezml" />
<meta name="copyright" content="Tezml" />
<meta name="description" content="Tezml" />
<script type="text/javascript" src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<div id="wz1"></div>
<div id="wz2"></div>
<div id="wz3"></div>
<div id="wz4"></div>
<div id="wz5"></div>
<div id="wz6"></div>
<div id="wz7"></div>
<div id="wz8"></div>
<div id="wz9"></div>
<div id="wz10"></div>
<div id="wz11"></div>
<div id="wz12"></div>
</body>
<script type="text/javascript">
var chinese="請叫我中文"
var english="place tall me englash"
var Monster=":#&$/@"
$("#wz1").html(encodeURI(chinese))//編碼 %E8%AF%B7%E5%8F%AB%E6%88%91%E4%B8%AD%E6%96%87
$("#wz2").html(decodeURI(chinese))//解碼 請叫我中文
$("#wz3").html(encodeURI(english))//編碼 place%20tall%20me%20englash
$("#wz4").html(decodeURI(english))//解碼 place tall me englash
$("#wz5").html(encodeURIComponent(Monster))//編碼 %3A%23%26%24%2F%40
$("#wz6").html(encodeURI(Monster))//編碼 :#&$/@
$("#wz7").html(escape(chinese))//編碼 %u8BF7%u53EB%u6211%u4E2D%u6587
$("#wz8").html(escape(english))//編碼 place%20tall%20me%20englash
$("#wz9").html(escape(Monster))//編碼 %3A%23%26%24/@
$("#wz10").html(unescape(chinese))//編碼 請叫我中文
$("#wz11").html(unescape(english))//編碼 place tall me englash
$("#wz12").html(unescape(Monster))//編碼 :#&$/@
</script>
</html>
總結
escape()不能直接用於URL編碼,它的真正作用是返回一個字符的Unicode編碼值。比如"春節"的返回結果是%u6625%u8282,,escape()不對"+"編碼 主要用於漢字編碼,現在已經不提倡使用。
encodeURI()是Javascript中真正用來對URL編碼的函數。 編碼整個url地址,但對特殊含義的符號"; / ? : @ & = + $ , #",也不進行編碼。對應的解碼函數是:decodeURI()。
encodeURIComponent() 能編碼"; / ? : @ & = + $ , #"這些特殊字符。對應的解碼函數是decodeURIComponent()。
假如要傳遞帶&符號的網址,所以用encodeURIComponent()