escape() 函数可对字符串进行编码,这样就可以在所有的计算机上读取该字符串。该方法不会对 ASCII 字母和数字进行编码,也不会对下面这些 ASCII 标点符号进行编码: * @ - _ + . / 。其他所有的字符都会被转义序列替换。
fromCharCode() 可接受一个指定的 Unicode 值,然后返回一个字符串。
所以Javascrip使用这两个函数结合就能实对汉字转实体码 unicode编码
<script type="text/javascript"> //http://www.bangnishouji.com/tools/chtounicode.html function action(pChoice){ switch(pChoice){ case "CONVERT_FMT1": $("#show2").val(ascii($("#source").val())); break; case "CONVERT_FMT2": $("#show2").val(unicode($("#source").val())); break; case "RECONVERT": $("#show2").val(reconvert($("#source").val())); break; } } function ascii(str){ return str.replace(/[^\u0000-\u00FF]/g,function($0){return escape($0).replace(/(%u)(\w{4})/gi,"\&#x$2;")}); } function unicode(str){ return str.replace(/[^\u0000-\u00FF]/g,function($0){return escape($0).replace(/(%u)(\w{4})/gi,"\\u$2")}); } function reconvert(str){ str = str.replace(/(\\u)(\w{4})/gi,function($0){ return (String.fromCharCode(parseInt((escape($0).replace(/(%5Cu)(\w{4})/g,"$2")),16))); }); str = str.replace(/(&#x)(\w{4});/gi,function($0){ return String.fromCharCode(parseInt(escape($0).replace(/(%26%23x)(\w{4})(%3B)/g,"$2"),16)); }); return str; } </script>
演示地址:汉字转Unicode