Node.js/Unicode
来自康健生活
< Node.js
引言
Unicode 与 String 互转(中文)
Unicode 转 String
eval("'" + string + "'");
当 string 中有带分号'或者"时,会报错,所以使用 eval('"' + string + '"'),eq:
eval("'" + '\u5eb7\u5efa' + "'");
"康建"
(new Function("return '" + string + "'"))();
(new Function("return '" + '\u5eb7\u5efa' + "'"))();
"康建"
unescape(string.replace(/\u/g, "%u"));
unescape('\u5eb7\u5efa'.replace(/\u/g, "%u"));
"康建"
String 转 Unicode
"\\u" + string.charCodeAt(i).toString(16);
"\\u" + '康建'.charCodeAt(0).toString(16);
"\\u" + '康建'.charCodeAt(1).toString(16);
"\u5eb7" "\u5efa"
Unicode 与 String 互转(中英文)
String 转 Unicode
中文 Unicode 是四位(eq: "\u5eb7"),而英文或者数字可能是两位(eq:"\u34")。JavaScript 并不能识别 "\u34",需要补全为 "\u0034"。
function string2unicode(str){
var ret ="";
var ustr = "";
for(var i=0; i<str.length; i++){
var code = str.charCodeAt(i);
var code16 = code.toString(16);
if(code < 0xf){
ustr = "\\u"+"000"+code16;
}else if(code < 0xff){
ustr = "\\u"+"00"+code16;
}else if(code < 0xfff){
ustr = "\\u"+"0"+code16;
}else{
ustr = "\\u"+code16;
}
ret +=ustr;
//ret += "\\u" + str.charCodeAt(i).toString(16);
}
var str_u = string2unicode("中国人CN");//"\u4e2d\u56fd\u4eba\u0043\u004e"
var str_s = unicode2string(str_u);//中国人CN
No categories