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

  1. create function isAlphanumeric() and take the input string as a parameter.
  2. Use regex to validate alphanumeric string
  3. 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.

javascript, check if a string contains only alphabets and numbers example
javascript, check if a string contains only alphabets and numbers or not example

I hope it’s help you, All the best 👍.