Skip to main content

How to Check if a String Contains Only Letters and Numbers in JavaScript

Validating strings to ensure they only contain alphanumeric characters is a common requirement for usernames, ID codes, or other data where special characters are not allowed. The most powerful and flexible tool for this job is a regular expression.

This guide will teach you how to use the RegExp.test() method with a simple regex to validate if a string is alphanumeric. We will also cover related tasks, such as allowing other specific characters and removing any non-alphanumeric characters from a string.

The Core Method: RegExp.test() with an Alphanumeric Regex​

The RegExp.prototype.test() method is the best tool for a simple true/false check. It tests a string for a match against a regular expression and returns a boolean.

Problem: you have a string and need to confirm it contains only letters and numbers, with no spaces, symbols, or other characters.

// Problem: How to validate these strings?
const str1 = 'Username123'; // Valid
const str2 = 'User Name'; // Invalid (contains a space)
const str3 = 'User-Name!'; // Invalid (contains symbols)

Solution: this function uses a simple regular expression to perform the check.

function isAlphanumeric(str) {
return /^[a-zA-Z0-9]+$/.test(str);
}

// Example Usage:
console.log(isAlphanumeric('Username123')); // Output: true
console.log(isAlphanumeric('User Name')); // Output: false
console.log(isAlphanumeric('User-Name!')); // Output: false
console.log(isAlphanumeric('')); // Output: false (due to `+`)

How the Regular Expression Works​

Let's break down the regex /^[a-zA-Z0-9]+$/:

  • /.../: The forward slashes enclose the regular expression pattern.
  • ^: Asserts the start of the string. This ensures the pattern must match from the very beginning.
  • [...]: Defines a character set. The pattern must match characters found inside these brackets.
    • a-z: Allows any lowercase letter.
    • A-Z: Allows any uppercase letter.
    • 0-9: Allows any digit.
  • +: A quantifier that means "one or more" of the preceding character set. This ensures the string is not empty.
  • $: Asserts the end of the string. This ensures there are no invalid characters after the alphanumeric part.

Together, ^ and $ anchor the expression, forcing the entire string to consist only of characters from the set.

Allowing Other Specific Characters (e.g., Spaces, Underscores)​

You can easily modify the character set to allow other specific symbols. For example, to create a validator for a username that allows letters, numbers, and underscores, you just add _ to the set.

function isValidUsername(str) {
// We added the underscore `_` to the character set.
return /^[a-zA-Z0-9_]+$/.test(str);
}

// Example Usage:
console.log(isValidUsername('My_User_123')); // Output: true
console.log(isValidUsername('My-User')); // Output: false (hyphen is not allowed)

You can add any other characters you want to permit directly inside the square brackets (e.g., ^[a-zA-Z0-9_ -]+$ to also allow spaces and hyphens).

How to Remove All Non-Alphanumeric Characters from a String​

Instead of validating a string, you might want to sanitize it by removing any invalid characters. The String.prototype.replace() method with a regular expression is perfect for this.

We use a negated character set ([^...]) to find any character that is not in our allowed set and replace it with an empty string.

function sanitize(str) {
// [^a-zA-Z0-9] matches any character that is NOT a letter or number.
// The 'g' flag ensures all occurrences are replaced, not just the first.
return str.replace(/[^a-zA-Z0-9]/g, '');
}

// Example Usage:
const dirtyString = 'User--Name!! (123)';
const cleanString = sanitize(dirtyString);

console.log(cleanString); // Output: UserName123

Conclusion​

Regular expressions are the definitive tool for validating string patterns in JavaScript.

  • To check if a string contains only alphanumeric characters, use the pattern /^[a-zA-Z0-9]+$/ with the .test() method.
  • To allow additional characters, simply add them to the character set inside the square brackets (e.g., ^[a-zA-Z0-9_]+$).
  • To remove all non-alphanumeric characters from a string, use the negated pattern /[^a-zA-Z0-9]/g with the .replace() method.

By mastering these simple regex patterns, you can write clean and reliable code for validating and sanitizing user input or other string data.