There are many ways we can use JavaScript to check if a string contains a letter. We will go over two simple methods below to do this.
The first uses the JavaScript test() method and a regex expression.
/[a-zA-Z]/.test(someString);
The regex expression /[a-zA-Z]/
will check for any letter, lowercase or uppercase. The test() method will check the string you pass as a parameter to see if a letter is contained in the string due to the regex expression. If it does find it, it returns true. Otherwise, it returns false.
We can wrap this code in a function to make it easy to reuse.
function stringContainsLetter(str){
return /[a-zA-Z]/.test(str);
};
Now let’s test this function with a couple of examples:
function stringContainsLetter(str){
return /[a-zA-Z]/.test(str);
};
var string1 = "This is a string with letters.";
var string2 = " ";
var string3 = "10000c23339";
var string4 = "123456";
var string5 = 12;
console.log(stringContainsLetter(string1));
console.log(stringContainsLetter(string2));
console.log(stringContainsLetter(string3));
console.log(stringContainsLetter(string4));
console.log(stringContainsLetter(string5));
#Output
true
false
true
false
false
Using JavaScript match() Method to Check if String Contains Letter
We can also use the match() method to check if a string contains a letter along with a regex expression as we did with the test method.
someString.match(/[a-zA-Z]/);
The match() method will search the string, someString, for whatever you pass in as the parameter, which in this case is our regex expression for a letter. The match() method will return an array with all of the matches, otherwise if a match is not found, it will return null.
Let’s put this code in a function as we did with the test() method.
function stringContainsLetter(str){
if( str.match(/[a-zA-Z]/) != null ){
return true;
} else {
return false;
}
};
And finally, let’s test this function as we did with our first function.
Now let’s test this function with a couple of examples:
function stringContainsLetter(str){
if( str.match(/[a-zA-Z]/) != null ){
return true;
} else {
return false;
}
};
var string1 = "This is a string with letters.";
var string2 = " ";
var string3 = "10000c23339";
var string4 = "123456";
console.log(stringContainsLetter(string1));
console.log(stringContainsLetter(string2));
console.log(stringContainsLetter(string3));
console.log(stringContainsLetter(string4));
#Output
true
false
true
false
Hopefully this article has been useful for you to learn how to use JavaScript to check if a string contains letter.