Determine whether Chinese characters and full-byte characters exist
Str. match (/[^ \ x00-\ xff]/ig)
Determine the length of a string containing Chinese Characters
AMatch = str. match (/[^ \ x00-\ x80]/g );
Str. length + (! AMatch? 0: aMatch. length)
Javascript determines the length of Chinese Characters
One type:
Copy codeThe Code is as follows:
Function _ length (str ){
Var len = 0;
For (var I = 0; I <str. length; I ++ ){
If (str. charAt (I)> '~ ') {Len + = 2;} else {len ++ ;}
}
Return len;
}
Two types:
Copy codeThe Code is as follows:
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;
}
String. prototype. gbtrim = function (len, s ){
Var str = '';
Var sp = s | '';
Var len2 = 0;
For (var I = 0; I <this. length; I ++ ){
If (this. charCodeAt (I)> 127 | this. charCodeAt (I) = 94 ){
Len2 + = 2;
} Else {
Len2 ++;
}
}
If (len2 <= len ){
Return this;
}
Len2 = 0;
Len = (len> sp. length )? Len-sp.length: len;
For (var I = 0; I <this. length; I ++ ){
If (this. charCodeAt (I)> 127 | this. charCodeAt (I) = 94 ){
Len2 + = 2;
} Else {
Len2 ++;
}
If (len2> len ){
Str + = sp;
Break;
}
Str + = this. charAt (I );
}
Return str;
}
Var str1 = 'World's best #%& World's Best #% ';
Document. write ('str1 = '+ str1 +'
');
Document. write ('length = '+ str1.gblen () +'
');
Document. write ('gbtrim (10) = '+ str1.gbtrim (10) +'
');
Document. write ('gbtrim (10 ,\'... \ ') =' + Str1.gbtrim (10 ,'... ') +'
');
Document. write ('gbtrim (12, \ '-\') = '+ str1.gbtrim (12,'-') +'
');
// Gbtrim (len truncation length, which is calculated based on the length of English bytes. The omitted characters After s truncation, such "... ")
// Note: Chinese characters are calculated as two lengths. Therefore, when len in gbtrim is 10, a maximum of five Chinese characters are displayed.
// When the number of Chinese characters is greater than 5, because "…" is added after the truncation, Therefore, only four Chinese characters are displayed.