Learning Regular Expressions (regex)

A very brief overview of regular expressions after finishing the lessons on FreeCodeCamp.org.

Last on my list of JavaScript education was most recently regular expressions, which are ways for a programmer to search for strings in text. I followed FreeCodeCamp’s (FCC) curriculum. You can find more about Regular Expressions on MDN.

The short name for regular expressions is “regex”, or “regexp”. The basic outline of a ‘regex’ goes like this, which tests if “Happy” is in thisLine:

let thisLine = "Happy happy, joy joy!"; 
let thisMatch = /Happy/; 
let outcome = thisMatch.test(thisLine); 
console.log(outcome);

The outcome is true. The test method only results in true or false.

In addition to test, you might also use match and replace. I believe those are the only 3 methods used in the FCC set of lessons.

Let’s try match. If you wanted to match “Happy”, and only “Happy”, you’d write:

let thisLine = "Happy happy, joy joy!"; 
let thisMatch = /^H[a-z]+/; 
let outcome = thisLine.match(thisMatch); 
console.log(outcome);

The outcome is [Happy]. Probably the most important part of regex is using special characters, and that’s what’s going on in this example. The special characters are shortcuts to help you search for a specific string. This examples searches for a string starting with a capital H (^H) and is following by any letter from a-z ([a-z]), and repeats the search for as long as necessary until reaching a break (like a space) (+).

An even simpler way to write the above would be to use a special character (\w) to search for any non-digit character and flags to allow upper or lower case (i), and global to search the entire string (g).

let thisLine = "Happy happy, joy joy!"; 
let thisMatch = /^H\w+/ig; 
let outcome = thisLine.match(thisMatch); 
console.log(outcome);

You can also return only non-alphanumeric or digit characters.

let thisLine = "Happy happy, joy joy!"; 
let thisMatch = /\W+/ig; 
let outcome = thisLine.match(thisMatch); 
console.log(outcome);

The outcome is [" ", ", ", " ", "!"]

There are many more examples of special characters, and I’ll be honest in admitting that I find it confusing. It took me a little while to figure out the second example above, partly because MDN separates their special characters onto different lines. Try these out in jsbin.

Anyway, regex are good to know if you need it.


From FreeCodeCamp:

Regular expressions are special strings that represent a search pattern. Also known as “regex” or “regexp”, they help programmers match, search, and replace text. Regular expressions can appear cryptic because a few characters have special meaning. The goal is to combine the symbols and text into a pattern that matches what you want, but only what you want. This section will cover the characters, a few shortcuts, and the common uses for writing regular expressions.