JavaScript Code

How to check if string contains only alphanumeric in JavaScript?


Check if string contains only alphanumeric

Given a string, check if the string contains only alphanumeric characters (alphabets and numbers), using JavaScript.

Solution

To check if given string str contains only alphanumeric characters using JavaScript, call match() method on the given string and pass a regular expression that matches one or more alphabets (upper or lower case) and numbers /^[A-Za-z0-9]+$/ as argument to the method.

str.match(/^[A-Za-z0-9]+$/)

The match() method returns true if the given string str contains only alphanumeric, or false otherwise. We can use this expression as a condition in if-else statement.

Programs

1. Given a string str. Check if this string contains only alphanumeric.

var str = 'HelloWorld1235';
if ( str.match(/^[A-Za-z0-9]+$/) ) {
    console.log('string contains only alphanumeric');
} else {
    console.log('string does not contain only alphanumeric');
}

Since the string contains only alphanumeric, if-block must run.

2. Given a string str. This string does contain some special characters and whitespaces. Check programmatically if this string contains only alphanumeric.

var str = 'HelloWorld@12 3';
if ( str.match(/^[A-Za-z0-9]+$/) ) {
    console.log('string contains only alphanumeric');
} else {
    console.log('string does not contain only alphanumeric');
}

Since the string does not contain only alphanumeric, else-block must run.