The input control has a Length attribute, allowing you to easily obtain the number of words. However, the number of words it returns, whether it is Chinese or English or a number, one word is one word. The customer needs to limit the number of words because the page display is not messy. Therefore, a Chinese character must be calculated based on two English characters. In this case, the default length will be useless.
How can we distinguish Chinese and English?
The string object has a method called charcodeat (INDEX) to obtain the encoding of a character in the string. We all know that the ASCII encoding of letters and numbers is less than 255, and the Chinese character encoding must be greater than 255. Therefore, we can use this method to determine the width of the string that occupies English characters. Function getcharlength (STR)
{
VaR ilength = 0;
For (VAR I = 0; I <Str. length; I ++)
{
If (Str. charcodeat (I)> 255)
{
Ilength + = 2;
}
Else
{
Ilength + = 1;
}
}
Return ilength;
}
The word count statistics are available. Next, we need to capture user input in real time. You can add a string detection function to the onkeyup event in the input text box.
After detecting the character length, we will remove the extra characters by truncation from the back to the front.
Character TruncationCodeFunction cutstr (STR, Len)
{
VaR curstr = "";
For (VAR I = 0; I <Str. length; I ++)
{
Curstr + = Str. charat (I );
If (getcharlength (curstr)> Len)
{
Return Str. substring (0, I );
}
}
Return curstr;
}
So far, a simple solution to limit the number of characters entered by users has been completed.
But it is not perfect.
The perfect solution is to use regular expressions.
In JavaScript, you can use a regular expression to search for and replace characters in a string. We can use this method to obtain the width occupied by the string. The Code is as follows: string. prototype. len = function (){
Return this. Replace (/[^ \ x00-\ xFF]/g, "**"). length;
}
This Code creates a Len attribute for the string object. You can directly use string. Len to obtain the width occupied by the string. Here, we use a small trick to use a regular expression to replace the characters encoded beyond 255 with two characters *, so that we can calculate the number.
For example:
If (uname. Len ()> 10 ){
$ ("Idtips"). innerhtml = "the length of the user name exceeds the limit ";
}
OK. By using the Len attribute, You can correctly determine the length of Chinese characters.