For some, a well-formed regex is a thing of beauty; for others, it’s the reason why there’s a bottle of ibuprofen nearby. Regardless of which group you fall into, it’s hard to deny that regular expressions are powerful tools, and any web developer would do well to become familiar (if not actually comfortable) with their use.
(This post is not a general introduction to regular expressions, so if that’s what you need, check out the resources below.)
Creating a regular expression in JS
use the backslash (
Or, you can create an instance of the RegExp object, in which case you do use quotes:
Any flags should be placed after the second delimiting backslash. In this example, the
i flag indicates case-insensitive matching:
MDN has a comprehensive list of available flags.
Using a regular expression in JS
Defining your regular expression is one thing; using it to search text is another. Thankfully, the JS RexExp object comes with several useful methods.
Testing for a match
To test for a match, pass the string to be search into the RexExp::test() method. This method will return true if the regex matches the string, otherwise false.
Obtaining matched text
If you need more information about a match than just whether it occurred, use the RexExp::exec() method. Calling exec() on a string will return
null if no match is found. Otherwise, it will return an object with more information about the match.
Check out these handy tools and resources about regular expressions: