Replacing Every Match With replaceAll()
In this lesson, you ported the helper’s first branch slug, which lowercases PAY-2291’s title and
puts a hyphen in place of every space, since git won’t take a branch name with spaces. In Python,
title.lower().replace(" ", "-") prints refund-emails-show-the-wrong-currency:-eur-shown-as-usd.
- The natural port,
title.toLowerCase().replace(" ", "-"), runs without an error but printsrefund-emails show the wrong currency: eur shown as usd: one hyphen, and the other eight spaces untouched. - Given text to find, JavaScript’s
replace()searches from the start, swaps the first match, and stops. Python’sreplace()changes every match unless you give it a count, andtitle.lower().replace(" ", "-", count=1)prints the port’s line. That’s where the likeness stops: JavaScript’sreplace()takes no count, and with plain text it changes one match. replaceAll()is the method that does what Python’sreplace()does, minus the count: it always changes every match. Swap the method’s name and the port prints Python’s slug, character for character.- Git doesn’t allow a colon in a branch name either, so the helper’s other replace removes it, and
that step joins the chain before the spaces turn into hyphens. On PAY-2291’s title,
replace(":", "")would give the same slug, but only because the title has one colon. Text with two, like the full header, keeps its second, so the chain usesreplaceAll(":", ""). - Use
replaceAll()for every match andreplace()when you mean only the first. With a regular expression instead of plain text,replace()can do more, but regular expressions are a later topic.
Here’s the slug with both steps in place:
const title =
"Refund emails show the wrong currency: EUR shown as USD";
const slug = title.toLowerCase()
.replaceAll(":", "").replaceAll(" ", "-");
console.log(slug);