[Solved] how to add line numbers to beginning of each line in string in javascript [closed]


var numbered = `Hi,
My
Name
is
Mike`.split('\n').map((line, index) => `${index + 1}. ${line}`).join('\n')

console.log(numbered)

Breaking down the solution;

  1. We take the original string and then split by the line-break character, so we get an array of strings (one per line)
  2. Map is a function that allows us to apply a transformation function to every item of the array, returning a new one with the new items.
  3. Map passes the current array item plus a zero based index. We concatenate the index with the current item so we get the string we expect
  4. Since we still have an array (but we need a string) we use join method. Join method joins all items in the array with a given character, in this case we pass the line break character again so we have one line per item.

1

solved how to add line numbers to beginning of each line in string in javascript [closed]