Node.js/Unicode:修订间差异
来自康健生活
创建页面,内容为“== 引言 == unicode编码与String互转 == Unicode 转 String ==” |
无编辑摘要 |
||
| (未显示同一用户的4个中间版本) | |||
| 第1行: | 第1行: | ||
== 引言 == | == 引言 == | ||
== Unicode 与 String 互转(中文) == | |||
== Unicode 转 String == | === Unicode 转 String === | ||
<blockquote> | |||
<syntaxhighlight lang="javascript"> | |||
eval("'" + string + "'"); | |||
</syntaxhighlight></blockquote> | |||
当 string 中有带分号'或者"时,会报错,所以使用 <code>eval('"' + string + '"')</code>,eq: | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
eval("'" + '\u5eb7\u5efa' + "'");</syntaxhighlight>|<pre> | |||
"康建" | |||
</pre>}} | |||
<blockquote> | |||
<syntaxhighlight lang="javascript"> | |||
(new Function("return '" + string + "'"))(); | |||
</syntaxhighlight></blockquote> | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
(new Function("return '" + '\u5eb7\u5efa' + "'"))();</syntaxhighlight>|<pre> | |||
"康建" | |||
</pre>}} | |||
<blockquote> | |||
<syntaxhighlight lang="javascript"> | |||
unescape(string.replace(/\u/g, "%u")); | |||
</syntaxhighlight></blockquote> | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
unescape('\u5eb7\u5efa'.replace(/\u/g, "%u"));</syntaxhighlight>|<pre> | |||
"康建" | |||
</pre>}} | |||
=== String 转 Unicode === | |||
<blockquote> | |||
<syntaxhighlight lang="javascript"> | |||
"\\u" + string.charCodeAt(i).toString(16); | |||
</syntaxhighlight></blockquote> | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
"\\u" + '康建'.charCodeAt(0).toString(16); | |||
"\\u" + '康建'.charCodeAt(1).toString(16);</syntaxhighlight>|<pre> | |||
"\u5eb7" | |||
"\u5efa" | |||
</pre>}} | |||
== Unicode 与 String 互转(中英文) == | |||
== String 转 Unicode == | |||
中文 Unicode 是四位(eq: "\u5eb7"),而英文或者数字可能是两位(eq:"\u34")。JavaScript 并不能识别 "\u34",需要补全为 "\u0034"。 | |||
<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> | |||