[Home] > Snippets  > Languages  > JavaScript  > Strings  >  Prepend a line number to each line of a text document

Prepend a line number to each line of a text document

JavaScript

const prependNumbers = (str) => str
.split(/\r?\n/)
.map((line, i) => `${(i + 1).toString().padStart(2, ' ')} ${line}`)
.join('\n')

TypeScript

const prependNumbers = (str: string): string => str
.split(/\r?\n/)
.map((line, i) => `${(i + 1).toString().padStart(2, ' ')} ${line}`)
.join('\n')

Examples

prependNumbers(`one
two
three
four
`
)

/* Output */
/*
1 one
2 two
3 three
4 four
*/