Emmanuel Akinfulubi

JavaScriptRegular expressions

Check if a string is alphanumeric in JavaScript

Beginner · 3 min read

"Letters and numbers only" is one of the most common rules in a form. Usernames, booking references, voucher codes and product codes often have it. Writing the check takes one short regular expression, and this tutorial explains every character in it.

There is a second question hiding in the exercise: whose letters? É, Ж and 中 are letters too. You will write an English-only version and an any-language version, and learn when each one is right. You need to know /.../.test(). The rest is explained as we go.

Classes, ranges and flags

Square brackets make a character class: "any one of these characters". A dash inside it makes a range. So [a-z0-9] means "one lower-case letter from a to z, or one digit from 0 to 9".

A letter after the closing slash is a flag that changes how the pattern behaves. The i flag ignores case, so [a-z] also matches capitals:

JavaScript

console.log(/[a-z]/.test('Q'));  // false
console.log(/[a-z]/i.test('Q')); // true

The whole string, not just part of it

^ means "the start of the text" and $ means "the end". + means "one or more". Put together, ^[a-z0-9]+$ says "from start to end, only letters and digits, at least one".

Without the anchors, the pattern is satisfied by a single good character anywhere:

JavaScript

console.log(/[a-z0-9]+/i.test('abc 123!')); // true, but there's a space and a !

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

10 Is the value alphanumeric?

easy

Check that a string contains only letters and digits. Then decide whose letters you mean.

Stuck? Three hints, smallest first
  1. 1. /^[a-z0-9]+$/i is the usual answer, and it is English-only.
  2. 2. /^[\p{L}\p{N}]+$/u means letters and numbers in any script.
  3. 3. Decide what an empty string should be, and make the decision visible.

Step 1: the English-only check

Step 1

const isAlphanumericAscii = (value) => /^[a-z0-9]+$/i.test(value);
console.log(isAlphanumericAscii('abc123'));  // true
console.log(isAlphanumericAscii('ABC'));     // true
console.log(isAlphanumericAscii('abc 123')); // false
console.log(isAlphanumericAscii('abc_123')); // false
console.log(isAlphanumericAscii(''));        // false

The space and the underscore are refused, which is what "letters and numbers only" means. The name ASCII refers to the basic English character set.

Step 2: decide about the empty string

The empty string fails because + needs at least one character. Swap + for * ("zero or more") and it passes:

JavaScript

console.log(/^[a-z0-9]*$/i.test('')); // true

Neither is wrong. A required field wants +; an optional field might be fine with *. Pick one on purpose, so you aren't surprised later.

Step 3: letters from any language

Try a French name:

JavaScript

const isAlphanumericAscii = (value) => /^[a-z0-9]+$/i.test(value);
console.log(isAlphanumericAscii('Étienne')); // false

É is not between a and z, so it is refused. For a reference code that is exactly right. For a person's name it turns real people away.

Regular expressions can match by Unicode property. \p{L} means "any letter in any script" and \p{N} means "any number". They only work with the u flag:

Step 3

const isAlphanumericUnicode = (value) => /^[\p{L}\p{N}]+$/u.test(value);
console.log(isAlphanumericUnicode('Étienne'));  // true
console.log(isAlphanumericUnicode('Жуков'));    // true
console.log(isAlphanumericUnicode('中文'));     // true
console.log(isAlphanumericUnicode('abc-123'));  // false

Dashes, spaces and symbols are still refused, so the rule keeps its meaning.

Step 4: one accent, two characters

An accented letter can be stored two ways: as one character é, or as a plain e followed by a separate accent mark (\u0301). They look the same on screen:

JavaScript

const isAlphanumericUnicode = (value) => /^[\p{L}\p{N}]+$/u.test(value);
const typed = 'e\u0301';
console.log(typed.length);                                  // 2
console.log(isAlphanumericUnicode(typed));                  // false
console.log(isAlphanumericUnicode(typed.normalize('NFC'))); // true

The accent mark on its own is not a letter, so the check fails. normalize('NFC') combines the pair into one character, and then it passes. Normalize text before you check or compare it.

The full solution

The panel runs both versions over the same list, including accented, Cyrillic and Chinese text. Press Run to see the rows where the two disagree.

The answer

const isAlphanumericAscii = (value) => /^[a-z0-9]+$/i.test(value);

// Any script: \p{L} is any letter, \p{N} any numeric character. The u flag is required.
const isAlphanumericUnicode = (value) => /^[\p{L}\p{N}]+$/u.test(value);

const cases = ['abc123', 'ABC', '123', 'Ade\u0301', '\u00c9tienne', '\u0416ukov', '\u4e2d\u6587',
  'abc 123', 'abc-123', 'abc_123', '', '\u20a6500', 'e\u0301'];

for (const v of cases) {
  console.log(JSON.stringify(v).padEnd(14),
    'ascii:', String(isAlphanumericAscii(v)).padEnd(6),
    'unicode:', isAlphanumericUnicode(v));
}
console.log('--- the + means one or more, so an empty string is refused ---');
console.log("with * instead:", /^[a-z0-9]*$/i.test(''), '<- an empty string would pass');

Output


      
18 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 18 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

18 checks

test('letters and digits pass', isAlphanumericAscii('abc123'), true);
test('letters alone pass', isAlphanumericAscii('ABC'), true);
test('digits alone pass', isAlphanumericAscii('123'), true);
test('a space is refused', isAlphanumericAscii('abc 123'), false);
test('a dash is refused', isAlphanumericAscii('abc-123'), false);
test('an underscore is refused', isAlphanumericAscii('abc_123'), false);
test('an empty string is refused, because of the +', isAlphanumericAscii(''), false);
test('with * it would pass, which is the decision to be explicit about', /^[a-z0-9]*$/i.test(''), true);
test('a currency symbol is refused', isAlphanumericAscii('\u20a6500'), false);
test('the ASCII version refuses an accented letter', isAlphanumericAscii('\u00c9tienne'), false);
test('the Unicode version accepts it', isAlphanumericUnicode('\u00c9tienne'), true);
test('and Cyrillic', isAlphanumericUnicode('\u0416ukov'), true);
test('and Chinese', isAlphanumericUnicode('\u4e2d\u6587'), true);
test('while still refusing a space', isAlphanumericUnicode('abc 123'), false);
test('and a dash', isAlphanumericUnicode('abc-123'), false);
test('a combining accent is a mark, not a letter, so it is refused', isAlphanumericUnicode('e\u0301'), false);
test('until it is normalised into one character', isAlphanumericUnicode('e\u0301'.normalize('NFC')), true);
test('the two versions disagree on non-English text', cases.some((v) => isAlphanumericAscii(v) !== isAlphanumericUnicode(v)), true);

/^[a-z0-9]+$/i is the expected answer. Whether it is the right answer depends entirely on what the field is for: as a check on a generated reference code it is exactly right, and as a check on a person's name it rejects Étienne and Жуков. /^[p{L}p{N}]+$/u is the same idea without that assumption.

Two details the assertions pin down. + versus * decides whether an empty string passes, and it is worth choosing on purpose rather than discovering later. And a combining accent — e followed by U+0301 — is a mark, not a letter, so even the Unicode version refuses it until normalize('NFC') combines the pair into a single character. Any text you compare or validate should be normalised first, because two strings that look identical on screen need not be equal.

Common mistakes

  • Forgetting ^ and $. Without them, one good character anywhere is enough to pass.
  • Using [a-z0-9] for names. It refuses everyone whose name has an accent or another alphabet. Use \p{L} with the u flag.
  • Leaving off the u flag. Without it, \p{L} is not read as "any letter", so the check stops working.

Try it yourself

  1. Allow spaces too, so 'Ada Obi' passes. (Hint: add a space inside the class.)
  2. Write isUsername(value) that allows English letters, digits and underscores, 3 to 16 characters long. (Hint: {3,16}.)
  3. Write isDigitsOnly(value) with /^\d+$/ and test it on '0803' and '08o3'.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.