用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)); //𠮷
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步