js实现的unicode和中文的相互转化
代码示例如下:
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 2 <html> 3 <head> 4 <title> Unicode to Chinese </title> 5 <meta name="Generator" content="EditPlus"> 6 <meta name="Author" content=""> 7 <meta name="Keywords" content=""> 8 <meta name="Description" content=""> 9 10 <script language="javascript"> 11 function unicode2chinese() { 12 var obj= document.getElementById("content"); 13 var strContent = obj.value; 14 //alert(strContent); 15 if (strContent==null||strContent.length==0) { 16 alert("please input unicode value"); 17 return; 18 } 19 var strTest=unescape(strContent.replace(/\\u/g,'%u')); 20 //alert(strTest); 21 //document.writeln(strTest); 22 obj.value=strTest; 23 } 24 25 function chinese2unicode() { 26 var objInChinese = document.getElementById("contentInChinese"); 27 var strContent = objInChinese.value; 28 //alert(strContent); 29 if (strContent==null||strContent.length==0) { 30 alert("please input chinese value"); 31 return; 32 } 33 34 var strTest=strContent.replace(/[^\u0000-\u00FF]/g,function($0){return escape($0).replace(/(%u)(\w{4})/gi,"&#x$2;")}); 35 strTest=strTest.replace(/;/g,''); 36 strTest=strTest.replace(/&#x/g,'\\u'); 37 //alert(strTest); 38 //document.writeln(strTest); 39 objInChinese.value=strTest; 40 } 41 </script> 42 </head> 43 <body> 44 <textarea name="content" id="content" rows="5" cols="100"></textarea> 45 <input type="button" name="btTransform" value="Unicode2Chinese" onclick="unicode2chinese();"/> 46 <p> 47 <textarea name="contentInChinese" id="contentInChinese" rows="5" cols="100"></textarea> 48 <input type="button" name="btTransformToUnicode" value="Chinese2Unicode" onclick="chinese2unicode();"/> 49 </body> 50 </html>
注意:存为html格式,可以直接运行!