查看“︁Node.js/Unicode”︁的源代码
来自康健生活
←
Node.js/Unicode
因为以下原因,您没有权限编辑该页面:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
== 引言 == == 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 互转(中英文) == == 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>
此页面嵌入的页面:
模板:Double-columns
(
查看源代码
)
模板:Double-columns/style.css
(
查看源代码
)
返回
Node.js/Unicode
。
导航菜单
康健生活
搜索
user-page
通知
user-interface-preferences
个人工具
登录
五一
多读书,多运动,多到远处走走,再看看不一样的世界。