Codewars: How to validate if a string is alphanumeric using regex.

I came across this question on Codewars that I found pretty interesting. Screenshot 2022-10-25 at 00.19.15.png

I had always avoided using regex as much as I could but this seemed like a good opportunity to sharpen my skills at it.

We're given a function with some sample test cases.

function alphanumeric(string){

}
  • alphanumeric("Mazinkaiser")should return true because it contains alphabets and no other symbols.
  • alphanumeric("hello world_") should return false because it contains an underscore which is neither an alphabet or a number.
  • alphanumeric("PassW0rd")should return true because it contains both an alphabet and a number.
  • alphanumeric(" ")should return false because it does not contain an alphabet or a number.

Seems pretty enough. Now, how can we solve this using regex?

function alphanumeric(string){
  if (string.match(/^[0-9a-z]+$/i)){
    return true
  }
  return false
}

What is going on in this function? It starts by checking if the string argument passed into the function matches the regular expression /^[0-9a-z]+$/i. I'll be explaining what each of those characters mean.

/: The / surrounding the expression is the boundary, defining the regular expression.

^: The caret symbol denotes the beginning of the expression. It means that we want our match to start in the beginning of our string.

[0-9a-z]: This is the range of characters we want to match our input against. We want numbers from 0-9 and alphabets from a-z.

+: This symbol means we want to match the preceding character one or more times (or at least once) . In our expression, we want it to check if the string value has at least one number or one alphabet.

$: Similar to the caret symbol (^) this denotes the end of a regular expression.

i: This tells the expression to ignore case. Rather than writing both A-Z and a-z, you can simply add i at the end of the regular expression.

All together, our function checks the string if it contains an alphabet, a number or both.

After I submitted my solution, I saw other similar solutions for the question.

The non-regex solution by VovaCodes

const alphanumeric = (str) => {
  if (!str.length) return false;
  const ALLOWED_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  for (let char of str) {
    if (!ALLOWED_CHARS.includes(char)) return false;
  }
  return true;
};

This was a pretty fun challenge. Let me know what you think and if I should continue with more posts like this!