JavaScript Code

How to check if string matches given regular expression in JavaScript?

If string matches given Regex

Given a string and regular expression (regex), check if the string matches the given regular expression, using JavaScript.


To check if the string str matches the regular expression regex using JavaScript, call test() method on the regex and pass str as argument to the method.


test() method returns true if the given string matches the regular expression, or false otherwise.


1. Given a string str and regular expression regex. The regular expression matches one or more characters from lowercase alphabets and numbers.

var str = 'abcd12345xyz';
var regex = /^[a-z0-9]+$/;
if ( regex.test(str) ) {
    console.log('string matches given regex');
} else {
    console.log('string does not match given regex');