汉字与unicode字符互相转换处理乱码

来源:互联网 发布:pc端软件开发 编辑:程序博客网 时间:2024/05/17 07:34

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<div id="div1">汉字与unicode字符转换</div>
<textarea id="uc" style="width:300px;height:150px;border:1px buttonface solid;"></textarea>
<br/>
<textarea id="txtboxA" name="txtboxA" style="width:300px;height:150px;border:1px buttonface solid;"></textarea>
<input type="button" value="Change Code To Unicode" onclick="CCTU(txtboxA.value,0);">
<br/>
<script language="javascript">
//unicode to chinese
var s = "&#20013";
var s = s.substr(2);//去掉&#
document.write(String.fromCharCode(parseInt(s,10)));//从Unicode字符值中返回一个字符串

a = "&#x6c88;&#x9633;a,b,c."
b = a.replace(/&#x/gi,"");//去掉&#
b= b.split(";")//分割字符串
for(i = 0;i<b.length-1;i++){
 document.write(String.fromCharCode(parseInt(b[i],16)));//从Unicode字符值中返回一个字符串
}

//chinese to unicode
function CCTU(str,htmlct){//writed by dh20156
 if(htmlct==null) htmlct = false;
 var rega = /^[/u4E00-/u9FA5]*$/;
 var regb = /([/uFF00-/uFF80])/;
 var regc = /。/;
 var regd = //r/;
 var newstr = new Array();
 var nid = 0;
 for(var i=0;i<str.length;i++){
  var ts = str.charAt(i);
  if(rega.test(ts) || regb.test(ts)){
   newstr[nid++] = "&#"+ts.charCodeAt(0)+";";//从指定位置上字符返回Unicode编码
  }else if(regc.test(ts)){
   newstr[nid++] = ".";
  }else if(regd.test(ts) && htmlct){
   newstr[nid++] = "<br/>";
  }else{
   newstr[nid++] = ts;
  }
 }
 document.getElementById("div1").innerHTML = newstr.join('');
 document.getElementById("uc").value = newstr.join('');
}
</script>
</body>
</html>

原创粉丝点击