Lesson 1
Introduction
What you'll learn
This course will take you from having no knowledge of regular expressions, to being able to read, write and understand them.
I can't promise that you'll never have to look anything up again, but I can promise that regular expressions will no longer look like strange collections of special characters.
Along the way, there will be interactive elements, mini-games to recap what we've learnt, and some helpful expressions you might find useful in real life.
We'll also try to make it as fun as possible 😊.
Let's go!!
What is a Regular Expression?
A regular expression (or 'regex' for short) is a pattern for searching text, like this:
/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
At first glance this looks like random characters, but it's actually an expression
to check whether a string represents a time in 24 hour format (HH:mm
).
This is the power of regular expressions. A single expression like this can be used to:
- Validate that an input is the correct format
- Extract a specific part (or parts) of a string
- Perform search-and-replace without complex string manipulation code
- .. and more!
Make a note to come back to this page later in the course.
The expression above will not only make sense then, but you'll recognise it as being quite basic.
Creating Regular Expressions
In the next lesson we'll start writing some regular expressions, but that won't mean much unless you know how to create them in JavaScript.
Literals
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/
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).
There are performance implications for either approach above.
We'll cover that in more detail later. For now, if you can use a Regular Expression Literal (which you can in most cases), then do that.