中文转换为n进制或Unicode

版权声明:未经同意,不得随意转载转载 https://blog.csdn.net/lucky541788/article/details/84703307

在给后端传递变量的的值中有汉字,可能由于编码的原因,传递到后端后变为乱码了。所以有时候为了省事或者其它特殊要求的时候,会把传递的汉字转换成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'
"哦"

猜你喜欢

转载自blog.csdn.net/lucky541788/article/details/84703307
今日推荐