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:CopyCodeThe 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 code The 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.