如何实现Unicode和ANSI编码格式字符串的相互转换

如题所述

一.字符串转化为Unicode编码
//方法1:
var str = "\\u6211\\u662Funicode\\u7F16\\u7801";

str = eval("'" + str + "'");

str = unescape(str.replace(/\u/g, "%u"));方法2:// 包装为JSON
var dataJSON = '{"Unicode编码": "'+ "\u7F16" +'"}';
// 使用JSON工具转换
var objJSON = JSON.parse(dataJSON);

var unicode = objJSON["Unicode编码"];
console.log(unicode); // 中文全月空格//二.将汉字转化为 unicode编码
var str = "中文";
// 获取字符
var char0 = str.charAt(0);
console.log(char0);// "中"
// 数字编码值
var code = str.charCodeAt(0);
console.log(code);// 20013
// 编码互转
var str0 = String.fromCharCode(code);
console.log(str0); // "中"
// 转为16进制数组
var code16 = code.toString(16);
console.log(code16);// "4e2d"
// 变成字面量表示法
var ustr = "\\u"+code16;
console.log("unicode编码",ustr ); // "\u4e2d"
温馨提示:答案为网友推荐,仅供参考
相似回答