Check if a string is alphanumeric in JavaScript
- Authors
- 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') // trueisAlphanumeric('Hello42') // trueisAlphanumeric('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
iflag makes it case-insensitive, soAtoZare allowed too. +requires at least one character, which is why an empty string returnsfalse.
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') // trueHere \p{L} matches any kind of letter and \p{N} matches any kind of number, with the u flag enabling Unicode mode.
Related
Need to create one instead of validate one? See generate a random alphanumeric string in JavaScript.
Related articles
Force an LLM to return JSON in JavaScript
Reliably get JSON from an LLM in JavaScript with OpenAI structured outputs and a Zod schema, instead of prompting for JSON and parsing fragile model text yourself.
The nullish coalescing operator (??) in JavaScript
What the double question mark (??) means in JavaScript: the nullish coalescing operator, how it differs from ||, and the ??= assignment shorthand.
LangChain JS agent with a custom tool
Create a small LangChain JavaScript agent with one custom tool using createAgent, tool, and a Zod schema, with a runnable end-to-end example.

