Line Prefixing (v2)

Revision 2 of this benchmark created on


Setup

const prefix = '[0] ';
const text = Array(100).fill('foo\nbar\nbaz').join('\n') + '\n';
const textForArray = text.slice(0);

Test runner

Ready to run.

Testing in
TestOps/sec
Split + Map + Join
textForArray.split('\n').map((line, i, lines) => {
	return i === lines.length - 1 ? line : prefix + line;
}).join('\n')
ready
Regex Replace with capture group
text.replace(/\n(.)/g, `\n${prefix}$1`)
ready
ReplaceAll
text.replace(/\n$/, '').replaceAll("\n", `\n${prefix}`)
ready
Regex Replace with function
text.replace(/\n/g, (_, i) => text[i + 1] ? '\n[0]' : '\n')
ready
ReplaceAll with function
text.replaceAll('\n', (lf, i) => lf + (text[i + 1] ? '[0]' : ''))
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.