Count characters in JavaScript, 2 characters in Chinese characters

Source: Internet
Author: User
Tags character set


The simplest str.length can be, examples

var str = "465464656464566";

var strlength = str.length;

Example 2, JS statistics string in the number of characters, 1 in Chinese 2 characters example:

<input type= "text"  id= "box"  size= " /> <input type=" button " onclick=" Countchar () " value=" Statistical characters  /> <script type= "Text/javascript" > Function countchar ()  { var textobj = document.getelementbyid (' box ');  var text = 
Textobj.value;
 var len = 0;  for  (var i = 0; i < text.length; i++)  {  if   (Text.charcodeat (i)  > 127)  {   len += 2;   } 
else {   len++;   }  }  alert (Len); </script> or regular function getstrlength (str)  {       var carr  = str.match (/[^\x00-\xff]/ig);       return str.length +   (carr == null ? 0 : carr.length);  }


Example 3, distinguishing character encoding

GBK Length calculation function:

&NBSP;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 is Chinese then length plus 2            

 realLength += 2;         }     }&nbsP

    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 is Chinese then length plus 3            

 realLength += 3;         }     }&nbSp

    return realLength; }

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.