JavaScript calculates the length of the string in Chinese and English

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.