Lesson 2

Basic Expressions

Introduction

To get us started, let's learn some simple expressions and get a feel for things...

Basic matching

Exact match

The simplest type of expression is the exact match.

As you might have guessed, this matches (or searches for) the exact text specified in the expression.

Writing this kind of expression is simple; just specify the string you wish to look for.

This is how we would define an expression to match the string 'think':

let expression = /think/
// or
let expression = new RegExp("think")

You can see this expression working in the interactive example below. Note that it only matches the word 'think', nothing else.

Try changing this expression to match other parts of the string:

Try it out!

What we think, we become.

- Buddha

Expression:>

You'll see a lot of these boxes throughout the course. ☝️

Experiment by changing the expression at the bottom of each, and observe how the behaviour changes.

Optional characters

If a character is optional in your search term, use a ? after it.

The ? token after a character means that the expression will 'match' whether that character is present or not.

The expression below matches both the UK and US spellings of the word 'color' (or 'colour') by making the u optional.

Remove the ? after the u character and see what happens:

Try it out!

What colour is this?

What color is this?

Expression:>

We say that the ? token matches the u character 'zero or one times'.

This is called a 'Quantifier'. We'll cover lots more of these later.

Modifiers

Modifiers change how the expression is interpreted.

Modifiers are specified at the end of the expression literal (after the final /), or in the second parameter of the RegExp constructor:

Here we add the g modifier (see below) to our expression:

let expression = /think/g
// or
let expression = new RegExp("think", "g")

We'll cover modifiers in more detail later, but there are a couple that you're more likely to use than others...

Global

The 'global' modifier tells the expression to find all possible matches in the string.

Without the g modifier, only the first instance of the expression will be matched.

Try removing the g modifier at the end of this expression and see what happens:

Try it out!

What we think, we become.

- Buddha

Expression:>

Case insensitive

The i modifier tells the expression to perform case-insensitive matching.

This expression matches all w characters, both upper and lower case. Remove the i modifier and see what happens:

Try it out!

What we think, we become.

- Buddha

Expression:>

Mini Game

Let's review what we've learnt with a little game!

Modify this regular expression so that it selects BOTH the US and UK spellings of honor/honour in this text:

It would be an honor your honour.


Your expression:

Hints:

  • You'll need to make the 'u' in 'honour' optional.
  • Remember to use the global modifier at the end.