Js string length contains the Chinese utf8 format

  • 2020-03-26 21:24:07
  • OfStack

Method one:


function byteLength(str) {
 var byteLen = 0, len = str.length;
 if( !str ) return 0;
 for( var i=0; i<len; i++ )
  byteLen += str.charCodeAt(i) > 255 ? 2 : 1;
 return byteLen;
}

Description: byteLength (STR)
Parameters:
String STR: a string to calculate the length of bytes (non-ascii characters count 2 bytes)

Method 2:

JS gets the actual length of the string!

Add a little thing today! A programmer often needs to use the string length detection method, because the original length of JS Chinese and English as a character for a length. So it's up to you to figure out what the actual length of the string is.


function GetLength(str) {
    /// <Summary> Get the actual length of the string, Chinese 2, English 1</ summary>
    /// <Param name = "STR"> To get a string of length </ param>
    var realLength = 0, len = str.length, charCode = -1;
    for (var i = 0; i < len; i++) {
        charCode = str.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128) realLength += 1;
        else realLength += 2;
    }
    return realLength;
};   

Execution code:

Alert (GetLength(' test tests ceshiceshi));      

Method 3: temporarily failed the test

 
function getByteLen(val) { 
var len = 0; 
for (var i = 0; i < val.length; i++) { 
if (val[i].match(/[u4e00-u9fa5 ]/ig) != null) 
len += 2; 
else 
len += 1; 
} 
return len; 
} 


Method 4:

GBK length calculation function:


//GBK character set actual length calculation
function getStrLeng(str){ 
    var realLength = 0; 
    var len = str.length; 
    var charCode = -1; 
    for(var i = 0; i < len; i++){ 
        charCode = str.charCodeAt(i); 
        if (charCode >= 0 && charCode <= 128) {  
            realLength += 1; 
        }else{  
            //If it's Chinese, the length is plus 2
            realLength += 2; 
        } 
    }  
    return realLength; 
}

UTF8 length calculation function:


//UTF8 character set actual length calculation
function getStrLeng(str){ 
    var realLength = 0; 
    var len = str.length; 
    var charCode = -1; 
    for(var i = 0; i < len; i++){ 
        charCode = str.charCodeAt(i); 
        if (charCode >= 0 && charCode <= 128) {  
            realLength += 1; 
        }else{  
            //If it's Chinese, the length is plus 3
            realLength += 3; 
        } 
    }  
    return realLength; 
}


Related articles: