JavaScript - String Contains Only Alphabetic Characters or Not
Here are several methods to check if a string contains only alphabetic characters in JavaScript
Using Regular Expression (/^[A-Za-z]+$/) - Most USed
The most common approach is to use a regular expression to match only alphabetic characters (both uppercase and lowercase).
let s = "HelloWorld";
let isAlphabetic = /^[A-Za-z]+$/.test(s);
console.log(isAlphabetic);
Output
true
This checks if the string contains only the letters A-Z and a-z. It will return true if all characters are alphabetic and false otherwise.
Using every() Method with Regular Expression
The every() method can be used with a regular expression to iterate over each character and verify it matches [A-Za-z].
let s = "HelloWorld";
let isAlphabetic = Array.from(s).every((char) =>
/[A-Za-z]/.test(char));
console.log(isAlphabetic);
Output
true
This approach works well for checking each character individually against the pattern.
Using for Loop with charCodeAt()
Using a for loop, you can check each character for alphabets without regular expressions.
let s = "HelloWorld";
let isAlphabetic = true;
for (let i = 0; i < s.length; i++) {
let code = s.charCodeAt(i);
if (!(code >= 65 && code <= 90) && !(code >= 97 && code <= 122)) {
isAlphabetic = false;
break;
}
}
console.log(isAlphabetic);
Output
true
Using every() with charCodeAt()
This method uses Array.from() to split the string into characters, then checks each one’s ASCII code.
let s = "HelloWorld";
let isAlphabetic = Array.from(s).every(char => {
let code = char.charCodeAt(0);
return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
});
console.log(isAlphabetic);
Output
true
Using isNaN() Function
To check if each character is non-numeric, you can use isNaN() along with checking for alphabetic ranges.
let s = "HelloWorld";
let isAlphabetic = Array.from(s).every(
(char) => isNaN(char) && /[A-Za-z]/.test(char)
);
console.log(isAlphabetic);
Output
true
Using filter() with match()
The filter() method can filter out non-alphabetic characters by checking each one with match(), and the length of the result should match the original string length if all are alphabetic.
let s = "HelloWorld";
let isAlphabetic =
s.split("").filter((char) =>
char.match(/[A-Za-z]/)).length === s.length;
console.log(isAlphabetic);
Output
true
The regular expression (/^[A-Za-z]+$/) remains the most efficient approach. However, methods like every() with charCodeAt() or a for loop offer flexibility for character-by-character validation.