Baby steps into Regular Expressions

ProgrammingJun 2021

Regular expressions are all but regular and yet they can be so damn useful. RegExp is a language of sorts that enables a programmer to express / signify a pattern of text. A pattern of text is a fancy way of saying something that can occur one or multiple times in a piece of text: the word dog; words that end in ing; phone numbers that start in 310, etc

A regular expression is an efficient way to determine if, for example, words that match one of the patterns mentioned above are present in a text document. Then, it can also be used to find those occurrences and replace them with something else (i.e. change all mentions of dog to cat).

Whereas such an operation can take a good amount of complexity to write; with a regular expression it can be greatly reduced – perhaps to one or two lines of code. Therefore, RegExps come in handy.

The Bones

In terms of their overall format, the regular expression is always encircled in two forward slashes and can be followed by what are referred to as flags.

These flags are the equivalent to a settings panel of the regular expression. They can be used to customize certain aspects of the searching and matching behavior. Things like finding all occurrences vs finding only the first one or finding occurrences regardless of them being upper or lower case.

So, say you want to find all instances of the word dog in a sentence. Simply write the word dog between two forward slashes, followed by the global flag.

Using a RegExp in real life

Even though a lot more can be said on how to express patterns with regular expressions, something I’m certain I’ll explore more in the future, at this stage it can be useful to rather focus on how to use them in Javascript.

The test() method is, perhaps, the simplest way to do so. It returns a boolean value of true or false depending on whether the regex is present or not.

Alternatively, the match() method returns null if not present, an array describing a single match, or a collection of all matches if it’s searching globally.

The RegExp Object

Now the fun begins. The RegExp object can be used to dynamically create a regular expression using a variable. This can be useful in a find and replace kind-of situation.

Here's an example of a find and replace method written using the RegExp object:

No items found.