RegExp syntax
Learn to create patterns with the RegExp literal and object.
What is a RegExp?
A RegExp (regular expression) searches for a pattern inside text. JavaScript gives you two ways to create one: a literal and a constructor.
const literal = /cat/;
const ctor = new RegExp("cat");Both represent the same pattern. The literal is short and readable; the constructor is handy when you build a pattern at runtime from a string, for example from a user's search term.
Flags
Add a flag at the end of a pattern to change how it behaves. The three most common flags are:
i— case-insensitive matchingg— find all matches (global)m— multiline mode
/cat/i.test("Cat"); // trueWith the constructor the flag is the second argument: new RegExp("cat", "i").
Exercise Test a cat pattern
Assign a regex literal matching "cat" to catPattern. Then test it on the string "concatenate" with .test() and log the result with console.log.
Show example solution
/cat/. The test method returns true/false.
Example solution:
let catPattern = /cat/;
console.log(catPattern.test("concatenate"));
Test yourself
-
Which is a valid RegExp literal?
- "/cat/"
- /cat/
- RegExp("cat")
- #cat#
Show answer
/cat/ — Correct! /cat/ is a regex literal; it goes between two slashes.
-
Make a dog pattern literal
const dogPattern = ____; console.log(dogPattern.test("hotdog"));Show answer
const dogPattern = /dog/; console.log(dogPattern.test("hotdog")); -
Match the creation forms
- /cat/
- literal
- new RegExp('cat')
- constructor
- /cat/i
- case-insensitive
- /cat/g
- global
-
Which flag makes matching case-insensitive?
- i
- g
- m
- s
Show answer
i — Correct! The i flag turns off case sensitivity.