首先由于正常的ASCII碼表示的字符有限,于是產生了Unicode, Unicode使用的是16進制的格式來表示一個字符.
在javascript里Unicode的表示格式有2種: 1. '%uxxxx' 2. '\uxxxx'.
在Java里Unicode格式就一種'\u'.
Javascript函數escape轉義的字符使用的就是'%u',于是這個hex到了java里就認不出來了,就會出現亂碼.
Solution:
1. 不管是'%u'或者'\u',他們都是hex在某種語言里的表示格式,真正的hex number還是在后面的數字. 所以只要把數字取出來加以處理就好了.
2. 數字取出來以后是16進制的,char和Integer 之間是可以隱式轉換的,我們現在要做的就是把16進制的數字轉換成10進制的Integer,然后轉換成char,對應的字符就出來了.
/**
* Decode given string.
* Java just know the hex form '\u2122', not know how to translate other form hex.
* If string include the javascript hex, like '%u2122'. This method will get the real hex number and cast it to right format char.
* @param input_str the string to decode
* @return an decode string
*/
public static String decodeFromHex(String input_str) {
Pattern p = Pattern. compile( "%u([a-zA-Z0-9]{4})");
Matcher m = p.matcher(input_str);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb,
String. valueOf(( char) Integer. parseInt(m.group(1), 16)));
}
m.appendTail(sb);
return sb.toString();