日期:2014-05-16  浏览次数:20461 次

js中unicod与ascii转换
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script language="JavaScript">
//ASCII->UNICODE
  function changeStr(){
var Str=document.form1.input.value;
var uniStr="";
for(var i=0;i<Str.length;i++){
var num=Str.charCodeAt(i);
if (num > 255 ){
  var ch="\\u"+num.toString(16);
  uniStr = uniStr+ch;
  }else{
uniStr =uniStr+Str.charAt(i);
  }
}
document.form1.output.value=uniStr;
return;
  }
 
  function changtoA() {
//Unicode -> ASCII
var code = document.form1.input.value.replace(/&#(\d+);/g).split("\\u");
if (code == null) {
alert('\u6587\u672c\u6846\u4e2d\u6ca1\u6709\u5408\u6cd5\u7684Unicode\u4ee3\u7801!');
return;
}
document.form1.output.value= "";
for (var i=0; i<code.length; i++){
if (code[i].length > 4) {
document.form1.output.value +=String.fromCharCode(parseInt(code[i].substr(0,4), 16));
document.form1.output.value +=code[i].substr(4);
} else {
document.form1.output.value +=String.fromCharCode(parseInt(code[i], 16));
}
}
return;
}
</script>
</head>
<body>
<form name="form1">
<textarea name="input" cols="100" rows="20"></textarea>
<br>
<input type="button" name="A2U" value="A->U" onclick="changeStr()"/><br>
<input type="button" name="U2A" value="U->A" onclick="changtoA()"/><br>
RESULT:<br>
<textarea name="output" value="" cols="100" rows="20"></textarea>
</form>
</body>
</html>