中文转换为n进制或Unicode

在给后端传递变量的的值中有汉字,可能由于编码的原因,传递到后端后变为乱码了。所以有时候为了省事或者其它特殊要求的时候,会把传递的汉字转换成Unicode编码后再进行传递。

自定义数字与中文转换:
  1. Code to Chinese:
function toChinese(str) {
    const matches = str.match(/(\\\d{3}){3}/g);
    if (matches) matches.forEach(match => {
        let decoded = '';
        const splits = match.split('\\');
        splits.forEach(code => !code || (decoded += '%' + parseInt(code, 8).toString(16)));
        const cChar = decodeURI(decoded);
        str = str.replace(match, cChar);
    });
    return str;
}

console.log(toChinese('\\345\\221\\265\\345\\221\\265')); // 呵呵
  1. Chinese to Code:
function toCode(str) {
    let matchs = encodeURI(str).match(/(%\w{2}){3}/g);
    var res='';
    if (matchs) matchs.forEach(match => {
        let encoded = '';
        const splits = match.split('%');
        splits.forEach(code => !code || (encoded += '\\' + parseInt(code, 16).toString(8)));
        res += encoded;
    });
    return res;
}

console.log(toCode('呵呵')); // \345\221\265\345\221\265

Unicode与中文转换:

  1. Unicode to Chinese
function toChinese(str) {
    str = str.replace(/\\/g, "%");
    return unescape(str);
}

console.log(toChinese('\u4f60\u597d')); // 你好
  1. Chinese to Unicode:
function toUnicode(s){
    return s.replace(/([\u4E00-\u9FA5]|[\uFE30-\uFFA0])/g,function(newStr){
        return "\\u" + newStr.charCodeAt(0).toString(16);
    });
}

console.log(toUnicode('你好')); // \u4f60\u597d
注意:

字符串转进制:

'好'.charCodeAt(0).toString(16)
"597d"
var str="Hello world!"
document.write(str.charCodeAt(1))
//结果:101

要想对Unicode解码的话,必须要用转义字符’\u’

// js unicode是以十六进制代码外加开头\u表示的字符串。即\unnnn
// Unicode 是为了解决传统的字符编码方案的局限而产生的
'\u54e6'
"哦"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值