js字符串编码和unicode编码互转

Posted 炫冰G爱

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js字符串编码和unicode编码互转相关的知识,希望对你有一定的参考价值。

//字符串编码转为unicode编码
function charToUnicode(str) { let temp; let i = 0; let r = ‘‘; let len = str.length; for (; i < len; i++) { temp = str.charCodeAt(i).toString(16); while ( temp.length < 4 ) temp = ‘0‘ + temp; r += ‘\\u‘ + temp; }; return r; }

  

//unicode编码转为字符串编码
function unicodeToChar(str){ //方案一 return eval("‘" + str + "‘"); //方案二 return unescape(str.replace(/\u/g, "%u")); }
//js获取字符串长度(字符真实个数)
//由于es5之前都将此类四个字节组成的字符"??"("??".length == 2)处理成2个长度,所以使用"for of"方法可以正确遍历字符串的长度
function getLength(str){
    let length = 0;
    for(let val of str){
        length++
    }      
    return length  
}

  

//codePointAt方法是测试一个字符由两个字节还是由四个字节组成的最简单方法。

function is32Bit(c) {
  return c.codePointAt(0) > 0xFFFF;
}

is32Bit("??") // true
is32Bit("啊") // false
is32Bit("a") // false

  

//实际使用中,一般设计会认为中文字符如‘啊‘,‘哦‘,‘额‘,‘,‘等理解为为两个长度,英文字符和数字如‘a‘,‘1‘,‘,‘等理解为为一个长度,所以此方法可以获取他们认为的字符串长度(注意,不是字符串的真是长度,只是设计师理解的长度)
function getViewLength(str){
    let length = 0;
    for (let c of str){//注意使用for of可以正确的遍历字符串的长度,而其他方法会将"??"当成两个长度遍历
        if(c.codePointAt(0) > 0x00FF){length = length + 2}//不管是两个字节的字符如‘啊‘,还是四个字节的字符‘??‘,都‘当成‘是属于两个字符长度的范围
‘ else{length++} } return length }

  

  



以上是关于js字符串编码和unicode编码互转的主要内容,如果未能解决你的问题,请参考以下文章

JS 中文 UTF-8编码互转

python3 Unicode字符与16进制编码互转(单个字符)

php 中文unicode 互转

php中文和unicode互转

python编码类型互转总结

JS 实现 unicode 中文互转