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.
The match() regex method can also be used for checking the match which retrieves the result of matching a string against a regex:
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.