var numbered = `Hi,
My
Name
is
Mike`.split('\n').map((line, index) => `${index + 1}. ${line}`).join('\n')
console.log(numbered)
Breaking down the solution;
- We take the original string and then split by the line-break character, so we get an array of strings (one per line)
- 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.
- 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
- 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]