javascript 中 unicode 和 String 类型互相转换
unicode 转 String
eval("'" + '\u5e74\u6708\u65e5' + "'")
unescape("\u5e74\u6708\u65e5")
String 转 unicode
"\\u"+parseInt('我'.charCodeAt(0),10).toString(16);
this.toUnicode = function (data) {
if (!data) return '参数错误, error';
var str = '';
for (var i = 0, len = data.length; i < len; i++) {
str += "\\u" + parseInt(data[i].charCodeAt(0), 10).toString(16);
}
return str;
}
toUnicode('爷爷在此')
var code = 'a'.charCodeAt(0);
var code16 = code.toString(16);
if(code < 0xf){
ustr = "\\u"+"000"+code16;
}else if(code < 0xff){
ustr = "\\u"+"00"+code16;
}else if(code < 0xfff){
ustr = "\\u"+"0"+code16;
}else{
ustr = "\\u"+code16;
}
console.log(ustr);
String 和 unicode 互转
function string2unicode(str){
var ret ="";
var ustr = "";
for(var i=0; i<str.length; i++){
var code = str.charCodeAt(i);
var code16 = code.toString(16);
if(code < 0xf){
ustr = "\\u"+"000"+code16;
}else if(code < 0xff){
ustr = "\\u"+"00"+code16;
}else if(code < 0xfff){
ustr = "\\u"+"0"+code16;
}else{
ustr = "\\u"+code16;
}
}
return ret ;
}