CodeBlanks Logo Icon CodeBlanks

RegExp syntax

JavaScript course · Intermediate · Lesson 118/134

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 matching
  • g — find all matches (global)
  • m — multiline mode
/cat/i.test("Cat"); // true

With 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

  1. 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.

  2. Make a dog pattern literal

    const dogPattern = ____;
    console.log(dogPattern.test("hotdog"));
    Show answer
    const dogPattern = /dog/;
    console.log(dogPattern.test("hotdog"));
  3. Match the creation forms

    /cat/
    literal
    new RegExp('cat')
    constructor
    /cat/i
    case-insensitive
    /cat/g
    global
  4. Which flag makes matching case-insensitive?

    • i
    • g
    • m
    • s
    Show answer

    i — Correct! The i flag turns off case sensitivity.

All lessons in Intermediate