javascript中unicode和String类型互相转换

这篇博客详细介绍了在JavaScript中如何进行Unicode和String类型的相互转换,包括两种将Unicode转为String的方法(eval和unescape)以及多种将String转为Unicode的策略,涉及到字符编码和解码的关键操作。此外,还提供了一个完整的字符串到Unicode转换的函数示例。
摘要由CSDN通过智能技术生成

javascript 中 unicode 和 String 类型互相转换

unicode 转 String

// unicode --> String
// 第一种方法
eval("'" + '\u5e74\u6708\u65e5' + "'")// 众所周知, 用eval的时候要特别注意空格, 建议在此处复制
// 第二种方法
unescape("\u5e74\u6708\u65e5")

String 转 unicode

// 1, 文字转 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('爷爷在此') // '\u7237\u7237\u5728\u6b64'
// 2, (单个)字母 转 unicode
	// 要特别注意, 字母和文字的转法并不一样, 一定要做好判断
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);// \u0061

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;
        }  
        // 把下面两行 其中一条 去掉注释符即可使用
        // ret +=ustr;                                    // unicode 转 字符
        // ret += "\\u" + str.charCodeAt(i).toString(16); // 字符 转 unicode
    }
    return ret ;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值