Lesson 7

Using Regular Expressions


You've come a long way! Now, it's time to use what we've learned.

In this lesson, we'll learn the various ways you can use Regular Expressions is JavaScript.

First, let's revisit what we learned way back in the first lesson...

Creating Regular Expressions

There are a couple of ways to create a regular expression in JavaScript:


If you know the regular expression at the point you are writing the code, define it using a Regular Expression Literal by surrounding it in //:

let expression = /something/

This is the syntax we'll use in this lesson, and is the one you're most likely to see in other codebases.

New RegExp

You can also define regular expressions using the RegExp constructor.

This allows you to pass a string representing the expression:

let expression = new RegExp('something')

This is useful if the expression is generated dynamically in your code, or comes from another source (such as API).

Using a Regular Expression

We've covered a lot of theory over the last 6 lessons, let's finally write some code!

The test() function

This is the simplest regular expression function. Pass it a string, and it will return true if the string matches the expression, otherwise false.

For example, this code checks for the word 'good' in a string.

Try modifying the sentence "I am bad at RegEx!" below, so that the test() function returns true instead:

Try it out!

let result = /good/.test("I am bad at RegEx!")

// result = false

The search() function

This function returns the location of the first match for a regular expression.

In the example below, our expression is using a set to look for any number from 0-9.

The example text contains two numbers ("3 apples and 1 orange"), and so the search() function returns 7, because the first of those is in position 7 in our string.

Add or remove some number from the text below, and see how the result changes:

Try it out!

let inputString "I have 3 apples and 1 orange."
let result = inputString.search(/[0-9]/)

// result = 7

We can use search() to do some pretty cool things!

In this example, we're grabbing just the extension (e.g. .com) from the end of somebody's email address.

Change the address below to see it in action:

Try it out!

let inputString "some.body@microsoft.co.uk"

let firstMatch = inputString.search(/(?<=@.*)\./)
let result = inputString.substring(firstMatch)

// result = ".co.uk"

Don't worry too much about the specifics of the /(?<=@.*)\./ expression we're using here, I know it looks confusing.

It uses something called a 'lookbehind' to find the first . that occurs after the @.

We'll learn about lookbehinds in a future lesson, so you're not expected to understand it right now.

The aim is just to show that search() can be quite useful for real things!

The match() function

If search() gives you the first match of an expression, how do we get all of the matches?

That's where match() comes in.

If you use pass a regular expression with the global flag to match(), it will return an array containing all of the matches:

// Match any number from 0-9 
"1 and a 2 and a 3 and a 4!".match(/[0-9]/g)

// ['1', '2', '3', '4']

If you don't pass a global expression, you'll still get an array - but it will contain the first match and the 'Capturing Groups' from your expression.

We'll learn about Capturing Groups (and the matchall() function, which is related to Capturing Groups) in the next lesson, so we won't talk any more about them here.

The replace() and replaceAll() functions

If you've done any string replacement in JavaScript already, you'll be familiar with these functions.

(if you're not, check out this section of Working With Strings in Modern JavaScript)

As you've probably guessed, they allow you to replace sections of a string, and they can also be used with regular expressions.

Here, we're using replace() to change all instances of the word 'baa' with 'moo' in a well-known nursery rhyme:

Try it out!

let inputString = "Here a baa, there a baa, everywhere a baa baa"
let result = inputString.replace(/baa/g, "moo")

// result = "Here a moo, there a moo, everywhere a moo moo"

Notice that we use the global modifier (g) at the end of this expression, which means we want to find all matches, not just the first. That's why all of the 'baa's are replaced.

If we remove the global modifier, only the first 'baa' is replaced:

Try it out!

let inputString = "Here a baa, there a baa, everywhere a baa baa"
let result = inputString.replace(/baa/, "moo")

// result = "Here a moo, there a baa, everywhere a baa baa"

You can also use JavaScript's replaceAll() function with regular expressions, but it's less flexible.

As implied by the name - it will only replace all matches. That means that you must pass a regular expression with the global modifier (g). If you don't, it will throw an exception.

Try it out!

let inputString = "Here a baa, there a baa, everywhere a baa baa"

let result = inputString.replaceAll(/baa/, "moo")
// Error: String.prototype.replaceAll called with a 
// non-global RegExp argument

The split() function

As implied by the name, this function allows us to split a string based on a regular expression.

You might already be aware that you can split a string using the .split() method without a regular expression.

For example, we could use split a date string into the day, month and year like this:

// ['30', '06', '1983']

So, why would we need to use regular expressions?

Back in Lesson 6 we learned about sets. Sets give us the ability to write a regular expression to match one or more characters.

This might be useful if we didn't know what separator was being used in the date string.

Here, we split the date based on either a /, . or a - character, using the expression [/.-]:

// ['30', '06', '1983']  

// ['30', '06', '1983']    

// ['30', '06', '1983']


What will this getQuote() function return?

let getQuote = () => {
    let quote = "You can if you think you can"
    return quote.replace(/can/, "can't")


Over the last 7 lessons, you learned the fundamentals of regular expressions and how to use them in code.

This is more than enough to get going, but in the next couple of lessons we'll cover some more advanced topics like 'look arounds' and 'capturing groups'.