Node.js/Unicode:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
创建页面,内容为“== 引言 == unicode编码与String互转 == Unicode 转 String ==”
 
Kangkk​(留言 | 贡献)
第1行: 第1行:
== 引言 ==
== 引言 ==
unicode编码与String互转
== Unicode 与 String 互转 ==
=== Unicode 转 String ===
<blockquote>
<syntaxhighlight lang="javascript">
eval("'" + string + "'");
</syntaxhighlight></blockquote>
 
当 string 中有带分号'或者"时,会报错,所以使用 <code>eval('"' + string + '"')</code>,eq:
 
{{Leftrightflex|<syntaxhighlight lang="javascript">
eval("'" + '\u5eb7\u5efa' + "'");</syntaxhighlight>|<pre>
"康建"
</pre>}}
 
<blockquote>
<syntaxhighlight lang="javascript">
(new Function("return '" + string + "'"))();
</syntaxhighlight></blockquote>
 
{{Leftrightflex|<syntaxhighlight lang="javascript">
(new Function("return '" + '\u5eb7\u5efa' + "'"))();</syntaxhighlight>|<pre>
"康建"
</pre>}}
 
<blockquote>
<syntaxhighlight lang="javascript">
unescape(string.replace(/\u/g, "%u"));
</syntaxhighlight></blockquote>
 
{{Leftrightflex|<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>
 
{{Leftrightflex|<syntaxhighlight lang="javascript">
"\\u" + '康建'.charCodeAt(0).toString(16);
"\\u" + '康建'.charCodeAt(1).toString(16);</syntaxhighlight>|<pre>
"\u5eb7"
"\u5efa"
</pre>}}
 
== Unicode 转 String ==
== Unicode 转 String ==