Getting started

So here’s the meat and potatoes of RegEx. The core of what it is to use Regular Expression. Let’s start at the beginning…

Declaring a RegEx method

There are a few ways to declare your Regular Expressions, the below is the easiest way I’ve found and is the most common.

The second method is a little bit more verbose as it uses the RegExp() method.

The RegExp constructor creates a regular expression object for matching text with a pattern. Fancy huh? With most things fancy, it’s also usually unnecessary. Use the first method.

‘Testing’ a Regular Expression

Now how do we see if our RegEx declaration matches a given string.

Luckily, a simple test method .test() is already in place natively to see whether your RegEx pattern matches or not, returning a boolean .

‘Executing’ the search for a particular match

The exec() method executes a search for a match in a specified string. Returns a result array, or null .

In this case, it will return an array.

Match

Though executing a pattern search is great, but what if we want to actually do the matching? Well I’ve got you covered with the .match() method.

The .match() method searches a string for a match against a regular expression, and returns the matches, as an Array object. However, in this case, we want to return the array with some further useful information like the specific instances our pattern occurs. We do this by appending the g (global) method to our reg variable declaration like this…

That now returns an array of instances that the pattern outlined in reg occurs.

Replace

Now you don’t always need to declare a regular expression pattern. You can always just use your string and a method. As is the case with the .replace() method.

Which simply just replaces whatever matches your pattern with something of your choice…

Search

Another cool regEx method is the .search() method which searches a string for a specified value, and returns the position of the match.

One of the great things about regEx is here in this method in that search value can be string or a regular expression. The customisability is quite varied and its why you’ll see so many differing opinions on what the best way to do anything in regEx is throughout the developer community.