用JavaScript實現漢字與Unicode的相互轉換


一、將漢字轉換為Unicode

 1 /*
 2  *將漢字轉換為Unicode
 3  *charCodeAt返回字符串指定位置的字符的Unicode編碼(十進制形式),在0-65535之間。
 4  *
 5  *toString(16) 將一個數字轉成十六進制。
 6  */
 7 function toUnicode(chineseStr) {
 8     if (chineseStr == '') {
 9         return 'Please input Chinese Characters';
10     }
11     let unicodeStr = '';
12     for (let i = 0, iLength = chineseStr.length; i < iLength; i++) {
13         unicodeStr += '\\u' + chineseStr.charCodeAt(i).toString(16);
14     }
15     return unicodeStr;
16 }
17 let s1 = '我是誰',
18     s2 = '𠮷';
19 console.log(toUnicode(s1)); //\u6211\u662f\u8c01
20 console.log(toUnicode(s2)); //\ud842\udfb7

二、將Unicode轉換為漢字

 1 /*
 2     將Unicode轉成漢字
 3     parseInt開始出了個小插曲,表明自己還是要多鞏固基礎,就是parseInt(string, radix)的第二參數radix,表示的是第一個參數string代表的
 4     數字的基數,而不是你最終解析的結果的基數,比如radix為16時,表示string是16進制的數字的字符串。parseInt的返回值始終是10進制表示的。
 5 
 6     fromCharCode: 將Unicode編碼為一個字符,可以有多個參數,即可以傳入多個Unicode值,然后再返回相應的多個字符。
 7 */
 8 function toChineseStr(unicodeStr) {
 9     if (unicodeStr == '') {
10         return 'Please input hexadecimal Unicode';
11     }
12     unicodeStr = unicodeStr.split('\\u');
13     let chineseStr = '';
14     for (let i = 0, iLength = unicodeStr.length; i < iLength; i++) {
15         chineseStr += String.fromCharCode(parseInt(unicodeStr[i], 16));
16     }
17     return chineseStr;
18 }
19 let c1 = '\\u6211\\u662f\\u8c01',
20     c2 = '\\ud842\\udfb7';
21 console.log(toChineseStr(c1)); //我是誰
22 console.log(toChineseStr(c2)); //𠮷

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM