Become a JavaScript RegEx Pro

Regular Expressions (RegEx) are an incredibly useful tool for any developer; from form validation to finding and replacing data amongst large datasets, they can be used for an encyclopedia of different situations. In my experience, RegEx has helped me becoming a more efficient developer, and making my code more compact. And I believe it can help you too.
To some developers, RegEx could feel like a maze at first; there are lots of rules, modifiers, and combinations. There’s overheard in the learning process, but it pays dividends.
I wrote this article to be a primer and cheat sheet for those that are trying to learn regular expressions. It includes important and commonly used features, as well as a walkthrough of the basics. Hopefully after reading this article you will have a better understanding of why that’s true and how to wield RegEx in your own projects, and you can return to this whenever you need a refresher.
So, let’s begin!
Regular Expressions have three main use cases:
Validation, Extraction and Replacement
regex.test(string)
The test method executes a search for a match between a regular expression and a specified string. It’s chained onto a regular expression and passed a string. Think of this method whenever you need to create a condition and want to execute code based on the existence of a pattern in a string.
Returns true or false.
string.match(regex)
The match method retrieves a pattern from a string. It’s chained onto a string and passed a regular expression. Think of this method whenever you need to extract and manipulate a pattern in a string.
Returns an array or null. The array will contain:
-
The matched pattern
-
Any patterns captured in parentheses,
-
An index, groups and input property.
-
When the /g flag is used, the array will only contain matches and no properties
string.replace(regex, replacement)
The replace method finds patterns in the original string and replaces those patterns. It takes two arguments, the RegEx to find patterns and a string to replace them. Think of this method when you have to strip out HTML from strings or update specific information.
Returns a new string.
The Basics
NOTE: in the examples below what follows the console.log() in blue is the return value.
You can search for Literal patterns using the exact characters.
You can search for multiple patterns using the Alternation or OR operator.
Inside a character set, you can define a Range of Characters to match with a hyphen.
If you found this useful, you can also dowload the cheat sheet in the link below:
Posted in regex