The length of the JavaScript calculation string is distinguished in English and Chinese:
Calculating the length of the string is a common operation and the code is as follows:
var str= "I Love Ant Tribe"; Console.log (str.length);
The length of the string is used to calculate the number of characters in the string, and in practice it may be necessary to calculate the byte length of the string, a Chinese character is two bytes, an English character occupies one byte, and the code is as follows:
var zfl={}; zfl. GetLength =function (str) { var reallength=0,len=str.length,charcode=-1; for (var I=0;i<len;i++ =str.charcodeat (i); if (charcode>0&&charcode<=128) reallength +=1; else reallength + = 2 return Reallength;} var str= "I Love Ant Tribe" ;console.log (ZFL. GetLength (str));
The above code to achieve our requirements, to distinguish between Chinese characters and English words, the following describes its implementation process.
I. Principle of implementation:
The principle is very simple, to determine whether the current character of the Unicode encoding value in a specified interval, through this interval can be judged by the Chinese character or English characters, if it is an English character that takes up a byte, if it is a Chinese character accounted for two bytes.
Two. Related reading:
The 1.for loop can be found in the section on the use of JavaScript for loop statements .
2. The charCodeAt () function can be a section of the charCodeAt () method of a String object of JavaScript .
The original address is: http://www.softwhy.com/forum.php?mod=viewthread&tid=11499
For more information, refer to: http://www.softwhy.com/javascript/
JavaScript calculates the length of the string in Chinese and English