Home >Web Front-end >JS Tutorial >5 ways to determine the length of a string in JS (distinguish between Chinese and English)_javascript skills

5 ways to determine the length of a string in JS (distinguish between Chinese and English)_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:55:172150browse

Purpose: Calculate the length of the string (English occupies 1 character, Chinese characters occupies 2 characters)

Method 1:

Copy code The code is as follows:

String.prototype.gblen = function() {
var len = 0;
for (var i=0; i if (this.charCodeAt(i)>127 || this.charCodeAt (i)==94) {
len = 2;
} else {
len ;
}
}
return len;
}

Method 2:
Copy code The code is as follows:
function strlen(str){
var len = 0;
for (var i=0; i var c = str.charCodeAt(i);
//Single byte plus 1
if (( c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
len ; > }
}
return len;
}

Method 3:



Copy code
The code is as follows: var jmz = {};jmz.GetLength = function(str) { ///Get the actual length of the string, Chinese 2, English 1< /summary>
///String to get the length
var realLength = 0, len = str.length, charCode = -1;
for (var i = 0; i < len; i ) {
charCode = str.charCodeAt(i);
if (charCode >= 0 && charCode <= 128) realLength = 1;
else realLength = 2;
}
return realLength;
};

Method 4:



Copy code
The code is as follows: var l = str.length; var blen = 0; for(i=0; iif ((str.charCodeAt(i) & 0xff00) != 0) {
blen ;
}
blen ;
}

Method 5:
Place the double Replace the byte into two single-byte ones and then get the length



Copy the code
The code is as follows: getBLen = function(str) { if (str == null) return 0; if (typeof str != "string"){
str = "";
}
return str.replace(/[^x00-xff]/g,"01").length;
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn