To check if a string contains only alphabets and numbers in JavaScript, you can use regular expressions.
In this example,
test
method of the regular expression to check if the string matches the pattern.containsOnlyAlphabetsAndNumbers
will be true
, otherwise false
.const str = 'Hello123';
const pattern = /^[a-zA-Z0-9]+$/;
const containsOnlyAlphabetsAndNumbers = pattern.test(str);
console.log(`String contains only alphabets and numbers: ${containsOnlyAlphabetsAndNumbers}`);
String contains only alphabets and numbers: true
In this tutorial, we learned How to Check if String contains only Alphabets and Numbers in JavaScript language with well detailed examples.