Check if a string is alphanumeric in JavaScript

Authors
  • avatar
    Name
    Hamza Rahman
Published on
-
2 mins read

A string is alphanumeric when every character is a letter or a digit, with no spaces, punctuation, or symbols. The simplest way to check this in JavaScript is a regular expression with test().

const isAlphanumeric = (str) => /^[a-z0-9]+$/i.test(str)
isAlphanumeric('abc123') // true
isAlphanumeric('Hello42') // true
isAlphanumeric('hello world') // false (has a space)
isAlphanumeric('user_name') // false (has an underscore)
isAlphanumeric('') // false (empty string)

How the regex works

  • ^ and $ anchor the match to the start and end, so the whole string must qualify, not just part of it.
  • [a-z0-9] allows lowercase letters and digits.
  • The i flag makes it case-insensitive, so A to Z are allowed too.
  • + requires at least one character, which is why an empty string returns false.

If you want to treat an empty string as valid, change + to *.

A note on Unicode

[a-z0-9] only covers the basic Latin alphabet. Accented or non-Latin letters like é or ä will return false. To accept letters and numbers from any language, use Unicode property escapes:

const isAlphanumericUnicode = (str) => /^[\p{L}\p{N}]+$/u.test(str)
isAlphanumericUnicode('café2') // true

Here \p{L} matches any kind of letter and \p{N} matches any kind of number, with the u flag enabling Unicode mode.

Need to create one instead of validate one? See generate a random alphanumeric string in JavaScript.