whatstheoutput_

#54: split() with a capturing group

Topic: strings · Difficulty: ★★★

console.log('2024-01-15'.split(/(-)/));

Output

[ '2024', '-', '01', '-', '15' ]

Why

When String.prototype.split() is given a regular expression, it normally discards the separator itself and keeps only the pieces between matches. But if that regular expression contains a capturing group — parentheses around part of the pattern — the captured text is ALSO spliced back into the result array, interleaved between the split pieces. Here /(-)/ captures the dash itself, so instead of just ['2024', '01', '15'], the dashes reappear in the output as their own array entries: ['2024', '-', '01', '-', '15']. This lets you split a string while still keeping the delimiters, which a non-capturing pattern like /-/ would throw away.

More strings puzzles

Play today's puzzle →