Splitting on the First Colon
In this lesson, you ported the helper’s first line, which takes PAY-2291’s header apart at its first
colon. The header has two colons, one after the key and one inside the title. In Python,
key, title = header.split(":", 1) gives the key and everything after the first colon, and the
helper prints Commit: PAY-2291: Refund emails show the wrong currency: EUR shown as USD.
- The natural port,
const [key, rawTitle] = header.split(":", 1);, unpacks an array, JavaScript’s version of a list (arrays get a course of their own later), with destructuring, the same shape as swapping with[a, b] = [b, a]. It stops on the next line withTypeError: Cannot read properties of undefined (reading 'trim'). - The second argument means different things. Python’s is
maxsplit: it counts splits and keeps the rest of the text in the last piece. JavaScript’s counts pieces, soheader.split(":", 1)is[ 'PAY-2291' ]andrawTitlegetsundefined. - On this header, Python’s split gives two pieces. A header with no colon gives it one, as in
"PAY-2291 Refund emails".split(":", 1), and then Python’s unpacking stops with aValueError. JavaScript’s destructuring fills the missing name withundefinedinstead, and the error comes a line later. - The repair
split(":", 2)runs without an error and printsCommit: PAY-2291: Refund emails show the wrong currency. With no second argument,split(":")works as it does in Python, cutting at every colon into three pieces; the limit caps how many of those pieces you keep, so2keeps the first two and silently drops: EUR shown as USD. - To split at the first separator only, find it with
indexOf()and slice either side.header.indexOf(":")is8, as Python’sfind()gives. Python’spartition()does the same job in one call, and JavaScript has no equivalent. - If there’s no colon,
indexOf()returns-1, asfind()does, and slicing with it quietly gives the wrong pieces in either language, so check for-1first when the input might not have a colon. Splitting on patterns is a later topic.
Here’s the port with the fix in place:
const header =
"PAY-2291: Refund emails show the wrong currency: " +
"EUR shown as USD";
const colon = header.indexOf(":");
const key = header.slice(0, colon);
const title = header.slice(colon + 1).trim();
console.log(`Commit: ${key}: ${title}`);