Hi Friends 👋,
Welcome To Infinitbility! ❤️
To check string is alphanumeric, use this regex /^[a-z0-9]+$/i
if it gets true means the string contains only alphabets and numbers.
Today, I’m going to show How do I check if a string is alphanumeric in javascript, here I will use the javascript test()
method and regex as mentioned above to validate whether the string is alphanumeric or not.
Let’s start the today’s tutorial How do you check if a string is alphanumeric in javascript?
In the following example, we are going to do
- create function
isAlphanumeric()
and take the input string as a parameter. - Use regex to validate alphanumeric string
- return boolean value based on string
let’s write the code.
function isAlphanumeric(str) {
return /^[a-z0-9]+$/i.test(str)
}
isAlphanumeric("infinitbility"); // ✅ true
isAlphanumeric("23"); // ✅ true
isAlphanumeric("23$"); // ⛔️ false
In the above program, we have created a custom function isAlphanumeric()
and passed a difference string example to validate the function.
let’s check the output.
I hope it’s help you, All the best 👍.