Method 1:
function byteLength(str) {
var byteLen = 0, len = str.length;
if( !str ) return 0;
for( var i=0; i byteLen = str.charCodeAt(i) > 255 ? 2 : 1;
return byteLen;
}
Description: byteLength(str)
Parameter:
string str: The string to calculate the byte length (non-ASCII characters count as 2 bytes)
Method 2:
JS gets the actual length of the string!
Another little thing added today! A string length detection method that programmers often use, because the original length of JS in Chinese and English is the same as one character. So here you have to judge and get the actual length of the string.
function GetLength(str) {
///
Get the actual length of the string, Chinese 2, English 1 ///
To get the length of the string
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;
};
Execution code:
alert(GetLength('Test test ceshiceshi));
Method 3: The test has not been passed yet
function getByteLen(val) {
var len = 0;
for (var i = 0; i < val.length; i ) {
if (val[i].match(/[u4e00-u9fa5 ]/ig) != null)
len = 2;
else
len = 1;
}
return len;
}
Method 4:
GBK length calculation function:
// 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 For Chinese, add 2 to the length
realLength = 2;
}
}
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 For Chinese, add 3 to the length
realLength = 3;
}
}
return realLength;
}
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