How to Check Whether a String Matches a RegEx in JavaScript

In this tutorial, we suggest two methods of checking whether your given string matches the RegEx. Suppose you want to check whether a string matches the following regex:

^([a-z0-9]{5,})$

The simplest and fastest method is the test() method of regex.

Javascript test method of regex
console.log(/^([a-z0-9]{4,})$/.test('ab1')); // false console.log(/^([a-z0-9]{4,})$/.test('ab123')); // true console.log(/^([a-z0-9]{4,})$/.test('ab1234')); // true

The match() regex method can also be used for checking the match which retrieves the result of matching a string against a regex:

Javascript match method of regex
var str = 'abc123'; if (str.match(/^([a-z0-9]{4,})$/)) { console.log("match!"); }
One of the differences between match() and test() methods is that the first works only with strings, the latter works also with integers.
Javascript match and test methods of regex
//12345.match(/^([a-z0-9]{5,})$/); // ERROR, match works only with strings console.log(/^([a-z0-9]{5,})$/.test(12345)); // true console.log(/^([a-z0-9]{5,})$/.test(null)); // false console.log(/^([a-z0-9]{5,})$/.test(undefined)); // true

However, test() is faster than match(). Use test() for a fast boolean check. Use match() for retrieving all matches when using the g global flag.

Javascript RegExp

Regex or Regular expressions are patterns used for matching the character combinations in strings. Regex are objects in JavaScript. Patterns are used with RegEx exec and test methods, and the match, replace, search, and split methods of String. The test() method executes the search for a match between a regex and a specified string. It returns true or false.