JavaScript中Unicode值转字符

时间:2024-09-03 19:35:44

  在JavaScript中,将Unicode值转字符的方法:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>JavaScript39</title>
<link rel="stylesheet" href="">
</head>
<body>
<input type="text" id="input1">
<p id="demo2"></p>
<button onclick="fromCharCode()">Unicode转换为字符串</button>
<script>
function groupArray(str){
var result = new Array();
for (var i = 0; i < str.length/2; i++) {
var aa = str.slice(i*2, (i+1)*2);
result.push(aa);
}
return result;
}
function fromCharCode(){
var m =document.getElementById("input1").value; //获取输入框的值
console.log(m);
var strArray = groupArray(m); //将输入框的值进行分组存放到数组里
console.log(strArray);
var charStr = "";
for (var i = 0; i < strArray.length; i++) {
var istr = strArray[i];
charStr = charStr.concat(String.fromCharCode(istr)); //将数组里的Unicode值转成字符串并连接起来
}
console.log(charStr);
document.getElementById("demo2").innerHTML = charStr; //将连接起来的值
}
</script>
</body>
</html>