Node.js/Unicode:修订间差异
来自康健生活
< Node.js
| 第48行: | 第48行: | ||
== Unicode 与 String 互转(中英文) == | == Unicode 与 String 互转(中英文) == | ||
== Unicode | == String 转 Unicode == | ||
中文 Unicode 是四位(eq: "\u5eb7"),而英文可能是三位(eq:)。 | |||
<syntaxhighlight lang="javascript"> | |||
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 </syntaxhighlight> | |||
2020年6月13日 (六) 16:07的版本
引言
Unicode 与 String 互转(中文)
Unicode 转 String
eval("'" + string + "'");
当 string 中有带分号'或者"时,会报错,所以使用 eval('"' + string + '"'),eq:
(new Function("return '" + string + "'"))();
unescape(string.replace(/\u/g, "%u"));
String 转 Unicode
"\\u" + string.charCodeAt(i).toString(16);
Unicode 与 String 互转(中英文)
String 转 Unicode
中文 Unicode 是四位(eq: "\u5eb7"),而英文可能是三位(eq:)。
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