W3docs

How to Check Whether a String Matches a RegEx in JavaScript

Read and learn two methods used to check whether a string matches RegEx in JavaScript. Also, see which method is the fastest and differences between them.

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:

Javascript regex

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

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

Javascript test method of regex

javascript— editable

The <kbd class="highlighted">match()</kbd> 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

javascript— editable
Info

One of the differences between <kbd class="highlighted">match()</kbd> and <kbd class="highlighted">test()</kbd> methods is that the first works only with strings, the latter works also with integers.

Javascript match and test methods of regex

javascript— editable

However, <kbd class="highlighted">test()</kbd> is faster than <kbd class="highlighted">match()</kbd>. Use <kbd class="highlighted">test()</kbd> for a fast boolean check. Use <kbd class="highlighted">match()</kbd> 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 <kbd class="highlighted">test()</kbd> method executes the search for a match between a regex and a specified string. It returns true or false.