Gets the actual length code for the Chinese string

  • 2020-03-30 03:14:33
  • OfStack

The default Chinese character length in JS is the same as other character length calculation methods, but in some cases we need to get the actual length of the Chinese string, the code is as follows:
 
function strLength(str) 
{ 
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; 
} 

Related articles: