一、将汉字转换为Unicode
/*
*将汉字转换为Unicode
*charCodeAt返回字符串指定位置的字符的Unicode编码(十进制形式),在0-65535之间。
*
*toString(16) 将一个数字转成十六进制。
*/
function toUnicode(chineseStr) {
if (chineseStr == '') {
return 'Please input Chinese Characters';
}
let unicodeStr = '';
for (let i = 0, iLength = chineseStr.length; i < iLength; i++) {
unicodeStr += '\\u' + chineseStr.charCodeAt(i).toString(16);
}
return unicodeStr;
}
let s1 = '我是谁',
s2 = '';
console.log(toUnicode(s1)); //\u6211\u662f\u8c01
console.log(toUnicode(s2)); //\ud842\udfb7
二、将Unicode转换为汉字
/*
将Unicode转成汉字
parseInt开始出了个小插曲,表明自己还是要多巩固基础,就是parseInt(string, radix)的第二参数radix,表示的是第一个参数string代表的
数字的基数,而不是你最终解析的结果的基数,比如radix为16时,表示string是16进制的数字的字符串。parseInt的返回值始终是10进制表示的。
fromCharCode: 将Unicode编码为一个字符,可以有多个参数,即可以传入多个Unicode值,然后再返回相应的多个字符。
*/
function toChineseStr(unicodeStr) {
if (unicodeStr == '') {
return 'Please input hexadecimal Unicode';
}
unicodeStr = unicodeStr.split('\\u');
let chineseStr = '';
for (let i = 0, iLength = unicodeStr.length; i < iLength; i++) {
chineseStr += String.fromCharCode(parseInt(unicodeStr[i], 16));
}
return chineseStr;
}
let c1 = '\\u6211\\u662f\\u8c01',
c2 = '\\ud842\\udfb7';
console.log(toChineseStr(c1)); //我是谁
console.log(toChineseStr(c2)); //