Get character length, Chinese 2 characters, English digit one character

Source: Internet
Author: User

Turn from TESTCS_DN (micro WX Laughter) Blog

Original URL: http://blog.csdn.net/testcs_dn/article/details/21412303#comments

Method One:

function strlen (str) {
var len = 0;
for (var i=0; i<str.length; i++) {
var c = str.charcodeat (i);
Single byte plus 1
if ((c >= 0x0001 && C <= 0x007e) | | (0xff60<=c && c<=0xff9f)) {
len++;
}
else {
len+=2;
}
}
return Len;
}

Method Two:

 

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

Method Three:

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

Method Four:

var jmz = {};

Jmz. GetLength = function (str) {
<summary> get string actual length, Chinese 2, English 1</summary>
<param name= "str" > string to get Length </param>
var reallength = 0, Len = str.length, charcode =-1;
for (var i = 0; i < len; i++) {
CharCode = Str.charcodeat (i);
if (charcode >= 0 && charcode <=) reallength + = 1;
else reallength + = 2;
}
return reallength;
};

Method Five:

String.prototype.gblen = function () {
var len = 0;
for (var i=0; i<this.length; i++) {
if (This.charcodeat (i) >127 | | this.charcodeat (i) ==94) {
Len + 2;
} else {
Len + +;
}
}
return Len;
}

Get character length, Chinese 2 characters, English digit one character

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.