Check if string contains only alphabets
Given a string, check if the string contains only alphabets, using JavaScript.
Solution
To check if given string str
contains only alphabets using JavaScript, call match()
method on the given string and pass a regular expression that matches one or more alphabets (upper or lower case) /^[A-Za-z]+$/
as argument to the method.
str.match(/^[A-Za-z]+$/)
The match()
method returns true
if the given string str
contains only alphabets, or false
otherwise. We can use this expression as a condition in if-else statement.
Programs
1. Given a string str
. Check if this string contains only alphabets.
var str = 'HelloWorld';
if ( str.match(/^[A-Za-z]+$/) ) {
console.log('string contains only alphabets');
} else {
console.log('string does not contain only alphabets');
}
Since the string contains only alphabets, if-block must run.
2. Given a string str
. This string does contain some digits also. Check programmatically if this string contains only alphabets.
var str = 'HelloWorld123';
if ( str.match(/^[A-Za-z]+$/) ) {
console.log('string contains only alphabets');
} else {
console.log('string does not contain only alphabets');
}
Since the string does not contain only alphabets, else-block must run.