Although js provides a function for calculating the number of bytes occupied by strings, it cannot correctly calculate the number of bytes occupied by Chinese characters, such as document. form1.username. value = "I am a Chinese", document. form1.username. value. length returns 5 instead of 10, which causes some trouble during programming, such as limiting the input of fixed-length characters and intercepting fixed-length strings, the following is a simple function written by myself. It is used to intercept fixed-length strings and is applicable to both Chinese and English. if anything is wrong, please correct it!
Copy codeThe Code is as follows:
// Js intercepts strings and can be used in both Chinese and English
// If the given string is greater than the specified length, return the string with the specified length. Otherwise, return the source string.
Function cutstr (str, len)
{
Var str_length = 0;
Var str_len = 0;
Str_cut = new String ();
Str_len = str. length;
For (var I = 0; I <str_len; I ++)
{
A = str. charAt (I );
Str_length ++;
If (escape (a). length> 4)
{
// The length of the Chinese character must be greater than 4 After encoding
Str_length ++;
}
Str_cut = str_cut.concat ();
If (str_length> = len)
{
Str_cut = str_cut.concat ("...");
Return str_cut;
}
}
// If the given string is smaller than the specified length, the source string is returned;
If (str_length <len ){
Return str;
}
}