Replacing Every Match With the g Flag

Your port now reads the whole log in one pass, with each commit’s hash, date, and subject by name. Before a ticket line reaches the team chat, though, the Python script rewrites two of its parts. It tidies the title, because PAY-2330 was committed as Payout report totals off by a cent, with two double spaces. It also turns the date around, so 2026-11-06 prints as 06/11.

Both jobs use re.sub() in Python. In this lesson, you’ll port them to JavaScript, along with Python’s other way to tidy spaces, split(). The first port of the title runs without an error and still prints the PAY-2330 line wrong, which is worth catching before the team chat sees it.

Collapse the Spaces in a Title

The Python script squeezes every run of whitespace in the title down to one space, strips the ends, and pads the result to 36 characters so the hashes line up:

Language: Python
import re

title = "Payout  report  totals off by a cent"
tidy = re.sub(r"\s+", " ", title).strip()
print(f"06/11  PAY-2330  {tidy:<36}0d9a6c3")

It prints 06/11 PAY-2330 Payout report totals off by a cent 0d9a6c3, with two spaces before the hash, so it lines up with every other ticket line.

JavaScript has no re.sub(). The .replace() method you already know from fixed text also accepts a regex as its first argument. With a string argument, .replace() changes only the first occurrence, and .replaceAll() changes them all.

In Python, r"\s+" carries no flags, so a line-by-line port uses /\s+/ with no flags and .trim() in place of .strip(). Predict how the PAY-2330 line compares with the finished PAY-2317 line:

Language: JavaScript
const title = "Payout  report  totals off by a cent";
const tidy = title.replace(/\s+/, " ").trim();
const sepa = "Add the SEPA mandate to receipts";

console.log(`06/11  PAY-2330  ${tidy.padEnd(36)}0d9a6c3`);
console.log(`04/11  PAY-2317  ${sepa.padEnd(36)}c2d4a61`);

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.