To check if a string contains only alphabets in JavaScript, you can use a regular expression.
In this example,
str1
with a value of "HelloWorld"
./^[a-zA-Z]+$/
to check if the string contains only alphabets.true
if the string contains only alphabets, otherwise false
.let str1 = 'HelloWorld';
let containsOnlyAlphabets = /^[a-zA-Z]+$/.test(str1);
console.log('String contains only alphabets:', containsOnlyAlphabets);
String contains only alphabets: true
In this example,
str2
with a value of "Hello123"
./^[a-zA-Z]+$/
to check if the string contains only alphabets.true
if the string contains only alphabets, otherwise false
.let str2 = 'Hello123';
let containsOnlyAlphabets = /^[a-zA-Z]+$/.test(str2);
console.log('String contains only alphabets:', containsOnlyAlphabets);
String contains only alphabets: false
In this tutorial, we learned How to Check if String contains only Alphabets in JavaScript language with well detailed examples.