Building Patterns With new RegExp()

With ^ in front, your ticket test works now, and /^(PAY-\d+): (.+)/i counts four ticket commits and three others, as the Python script does. But the Python pattern doesn’t hard-code PAY. The card team and the ledger team generate the same release notes with their own key, so the team lead keeps it in one setting at the top of the file.

A regex literal can’t hold a variable, so this lesson builds the pattern from text instead. You’ll see why the port that looks most like the Python code matches nothing without an error, and how JavaScript developers write patterns that come from a setting.

Build the Pattern From the Team Setting

In the Python script, the team key is a constant, and an rf-string drops it into the pattern:

Language: Python
import re

TEAM = "PAY"
TICKET = re.compile(rf"({TEAM}-\d+): (.+)", re.IGNORECASE)

The f fills in {TEAM}, and the r keeps \d exactly as written. JavaScript’s slashes work like Python’s r prefix, but there’s no way to put a variable between them. To build a pattern from a string, you call new RegExp(text, flags), where new creates a RegExp object the way new Intl.NumberFormat() creates a formatter. RegExp() takes the pattern as its first argument and the flags as a string of letters, here "i".

The template literal is JavaScript’s f-string, so a line-by-line port puts the two together. It keeps the ^ from the last lesson because .test() searches anywhere, like re.search(). Before you run it, predict what the test on the newest commit’s subject prints:

Language: JavaScript
const TEAM = "PAY";
const TICKET = new RegExp(`^(${TEAM}-\d+): (.+)`, "i");

console.log(
  TICKET.test("PAY-2330: Payout report totals off by a cent"),
);

There’s no error, and the answer is no:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.