Basic Intro
Regular expressions are not something you need to learn and master as a beginner. We just want you to get a preliminary understanding of Regular Expressions, also referred to as 'regexp'.
The most common use of regular expressions is to find matching sequences of characters in searches. Usually this pattern is used by string searching algorithms for "find" or "find and replace" operations on strings.
Two Ways to Create a RegExp
Literal
Constructor Function
A sample
Here's the issue: The writers of our website have written all the copy with us being listed as Eleven Fifty Consulting rather than Eleven Fifty Academy. We need to do two things: 1. Find all the instances of Eleven Fifty Consulting. 2. Replace all of them with Eleven Fifty Academy.
We'll break this down into small chunks. Here's a sample string to work with:
Notice how we're using backticks in that string instead of quotes. This is not part of regular expressions. Backticks are an ES6 feature that allows us to write multi-line strings without having to use any escape characters. We'll use this efaString
in all of the following examples.
Match Function
Next, we'll write a function that checks for the word consulting.
Notice, the patternOne
variable inside the function? That is a simple regular expression. That dictates the sequence of characters that we are trying to match. So the first variable, sets up the sequence that we're looking for. The g
on the end dicates that we'll be looking globally, throughout the whole string sequence.
The second variable takes the sampleString that is passed in and calls the .match()
method. The argument that we pass in to that method is the regular expression pattern that we are looking for. The match
method does the work of taking the regular expression and it looks for matches inside of the string that is passed into the function.
Finally, we log the result.
replace() method
Next, lets write a method that actually does the work of replacing 'Consulting' with 'Academy':
Here we see a similar process. We look for patternOne
globally. We set up another variable, a simple string variable, that will be what we used to replace the incorrect text. Then, we have a newString
variable that takes the sampleString
and calls the replace()
method.
Replace takes two arguments: the pattern to be found, and the pattern to use as a replacement.
In the end, we console.log the new string.
More practice
Our writers also get confused on the word 'their', spelling it thier
. Write a function that takes in the efaString, finds any incorrect spellings of 'their', and replaces it with the proper spelling.
Last updated