JS Judge string Length (Chinese length is 2, English length is 1)

Source: Internet
Author: User

Purpose: To calculate the length of a string (1 characters in English, 2 characters in Chinese character)

Method One:

function () {    var len = 0;      for (var i=0; i<this. Length, i++) {      if (this). charCodeAt (i) ==94) {         + =2       ; Else  {         ++;       }     }     return len;  }

Method Two:

functionstrlen (str) {varLen = 0;  for(vari=0; i<str.length; i++) {      varc =str.charcodeat (i); //single byte plus 1     if((c >= 0x0001 && C <= 0x007e) | | (0xff60<=c && c<=0xff9f) ) {len++; }      Else{len+=2; }     }     returnLen;}

Method Three:

varJMZ ={};jmz. GetLength=function(str) {///<summary> Get string actual length, Chinese 2, English 1</summary>  ///<param name= "str" > string to get length </param>  varReallength = 0, Len = str.length, charcode = 1;  for(vari = 0; i < Len; i++) {CharCode=str.charcodeat (i); if(charcode >= 0 && charcode <=) Reallength + = 1; ElseReallength + = 2; }  returnreallength;};

Method Four:

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

Method Five:

Replace the double-byte with two single-byte and then get the length

function (str) {  ifnullreturn 0;   if (typeof str! = "string")    {+ = "";  }   return str.replace (/[^\x00-\xff]/g, "n"). Length;

JS Judge string Length (Chinese length is 2, English length is 1)

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.