Home  >  Article  >  Web Front-end  >  JavaScript fun question: Does a string consist of letters or numbers?

JavaScript fun question: Does a string consist of letters or numbers?

黄舟
黄舟Original
2017-01-22 14:51:331842browse

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)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn