1. 程式人生 > >中文轉換為n進位制或Unicode

中文轉換為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'
"哦"