We can use JavaScript to check if a string contains only letters. One of the simplest ways to do this is to use 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 upper. The rest of the regex expression checks that every character in the string is equal to a letter. Here is a useful resource on regex expressions if you want to learn more about them. The test() method will check the string you pass as a parameter to see if only letters are contained in the string due to the regex expression. If it does find all letters, it returns true. Otherwise, it returns false.
We can wrap this code in a function to make it easy to reuse.
function stringContainsOnlyLetters(str){
return /^[a-zA-Z]+$/.test(str);
};
Now let’s test this function with a couple of examples:
function stringContainsOnlyLetters(str){
return /^[a-zA-Z]+$/.test(str);
};
var string1 = "This is a string with letters and spaces";
var string2 = "Thisisastringwithonlyletters";
var string3 = "Hello";
var string4 = "hello";
var string5 = "This is a string with letters and spaces and a period.";
console.log(stringContainsOnlyLetters(string1));
console.log(stringContainsOnlyLetters(string2));
console.log(stringContainsOnlyLetters(string3));
console.log(stringContainsOnlyLetters(string4));
console.log(stringContainsOnlyLetters(string5));
#Output
false
true
true
true
false
If we wanted to make all of these examples return true by allowing spaces and periods, we would simply need to our regular expression.
function stringContainsLettersSpacesPeriods(str){
return /^[a-zA-Z .]+$/.test(str);
};
var string1 = "This is a string with letters and spaces";
var string2 = "Thisisastringwithonlyletters";
var string3 = "Hello";
var string4 = "hello";
var string5 = "This is a string with letters and spaces and a period.";
console.log(stringContainsLettersSpacesPeriods(string1));
console.log(stringContainsLettersSpacesPeriods(string2));
console.log(stringContainsLettersSpacesPeriods(string3));
console.log(stringContainsLettersSpacesPeriods(string4));
console.log(stringContainsLettersSpacesPeriods(string5));
#Output
true
true
true
true
true
Hopefully this article has been useful for you to learn how to use JavaScript to check if a string contains only letters.
Leave a Reply