SoFunction
Updated on 2025-03-06

Simple way to get the actual length of a string (including Chinese characters) by JS

Method 1:

var jmz = {};
 = function(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 = , charCode = -1;
  for (var i = 0; i &lt; len; i++) {
    charCode = (i);
    if (charCode &gt;= 0 &amp;&amp; charCode &lt;= 128) 
       realLength += 1;
    else
       realLength += 2;
  }
  return realLength;
};

alert(('Test testceshiceshi));

Method 2 (a more concise method):

var l = ;
var blen = 0;
for(i=0; i<l; i++) {
if (((i) & 0xff00) != 0) {
blen ++;
}
blen ++;
}

Method 3 (a more concise method):

var jmz = {};
 = function(str) {
  return (/[\u0391-\uFFE5]/g,"aa").length;  //First replace Chinese with two bytes of English, calculate the length};  
alert(('Test test ceshiceshi'));

The simple way to get the actual length of a string (including Chinese characters) in the above article is all the content I share with you. I hope you can give you a reference and I hope you can support me more.