js對文字進行編碼涉及3個函數:escape,encodeURI,encodeURIComponent,相應3個解碼函數:unescape,decodeURI,decodeURIComponent
1、 傳遞參數時需要使用encodeURIComponent,這樣組合的url才不會被#等特殊字元截斷。
例如:<script language="javascript">document.write('<a href="http://passport.baidu.com/?logout&aid=7&u='+encodeURIComponent("http://cang.baidu.com/bruce42")+'">退出</a>');</script>
2、 進行url跳轉時可以整體使用encodeURI
例如:Location.href=encodeURI("http://cang.baidu.com/do/s?word=百度&ct=21");
3、 js使用資料時可以使用escape
[Huoho.Com編輯]
例如:搜藏中history紀錄。
4、 escape對0-255以外的unicode值進行編碼時輸出%u****格式,其它情況下escape,encodeURI,encodeURIComponent編碼結果相同。
最多使用的應為encodeURIComponent,它是將中文、韓文等特殊字元轉換成utf-8格式的url編碼,所以如果給後台傳遞參數需要使用encodeURIComponent時需要後台解碼對utf-8支援(form中的編碼方式和當前頁面編碼方式相同)
escape不編碼字元有69個:*,+,-,.,/,@,_,0-9,a-z,A-Z
encodeURI不編碼字元有82個:!,#,$,&,',(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a-z,A-Z
encodeURIComponent不編碼字元有71個:!, ',(,),*,-,.,_,~,0-9,a-z,A-Z
java.net.URLDecoder / java.net.URLEncoder
對應的是javascript的 encodeURI/decodeURI 和 encodeURIComponent/decodeURIComponent 吧?
下面的java對應的是javascript 的escape/unescape
|
java版本的escape和unescape函數 |
class EscapeUnescape { public static String escape (String src) { int i; char j; StringBuffer tmp = new StringBuffer(); tmp.ensureCapacity(src.length()*6); for (i=0;i<src.length() ;i++ ) { j = src.charAt(i); if (Character.isDigit(j) || Character.isLowerCase(j) || Character.isUpperCase(j)) tmp.append(j); else if (j<256) { tmp.append( "%" ); if (j<16) tmp.append( "0" ); tmp.append( Integer.toString(j,16) ); } else { tmp.append( "%u" ); tmp.append( Integer.toString(j,16) ); } } return tmp.toString(); } public static String unescape (String src) { StringBuffer tmp = new StringBuffer(); tmp.ensureCapacity(src.length()); int lastPos=0,pos=0; char ch; while (lastPos<src.length()) { pos = src.indexOf("%",lastPos); if (pos == lastPos) { if (src.charAt(pos+1)=='u') { ch = (char)Integer.parseInt(src.substring(pos+2,pos+6),16); tmp.append(ch); lastPos = pos+6; } else { ch = (char)Integer.parseInt(src.substring(pos+1,pos+3),16); tmp.append(ch); lastPos = pos+3; } } else { if (pos == -1) { tmp.append(src.substring(lastPos)); lastPos=src.length(); } else { tmp.append(src.substring(lastPos,pos)); lastPos=pos; } } } return tmp.toString(); } public static void main(String[] args) { String tmp="~!@#$%^&*()_+|\\=-,./?><;'][{}\""; System.out.println("testing escape : "+tmp); tmp =escape(tmp); System.out.println(tmp); System.out.println("testing unescape :"+tmp); System.out.println(unescape(tmp)); } }
|
|