Sometimes, you need to verify whether an input string consists of only letters or numbers. An English word just explains this requirement - alphanumeric.
Further refine this requirement:
1. The string consists of at least one character (that is, an empty string cannot pass)
2. Uppercase and lowercase English is allowed Letters, numeric characters from 0 to 9 (this is the main one)
3. As long as other characters appear, they will be 100% blocked, such as spaces and underscores.
Regarding this problem, students who are proficient in using regular expressions can just say one sentence, but what should we do if we don’t use regular expressions?
is also very simple. You can use ASCII code to judge the string one by one.
Let’s first look at some ASCII code ranges:
1. Numeric characters 48-57
2. Capital letters 65-90
3. Lowercase The letters 97-122
within these ranges are all valid characters, so those outside the range must be illegal characters.
But don’t forget the special case mentioned above-the empty string.
Okay, with these information, we can write it out effortlessly.
function alphanumeric(string){ if(string.length < 1){ return false; } for(var i=0;i<string.length;i++){ var code = string.charCodeAt(i); if(code < 48 || code > 57 && code < 65 || code > 90 && code < 97 || code > 122){ return false; } } return true; }
The above is an interesting JavaScript question: Is a string composed of letters or numbers? For more related content, please pay attention to the PHP Chinese website (www.php.cn)!