Split a string by word and detect/include line breaks

In order to animate headings word by word, I’m trying to split a string by space, but the CMS I use returns line breaks as n inside of the string.

const text = "Aenean non odio erat.n Suspendisse vestibulum vulputate nulla et mollis."

const splitText = (text) => {
    const words = text.split(' ')
    return words
}

console.log(splitText(text))

Using this code, I get this result:

[
  "Aenean",
  "non",
  "odio",
  "erat.n",
  ...
]

How to split the string by word but keep including and visually show (maybe with CSS using white-space: wrap; or pre-wrap) the line breaks?

Answer

The idea is to “normalize” whitespaces first, and then split by a space, so that newlines “stick” to the preceding word:

const text = "Aenean non odio erat.nSuspendisse vestibulum n n n    vulputatennnulla et mollis."

const splitText = text => text
  .replace(/\n/g, 'n')
  .replace(/s+/g, m => m.includes('n') ? 'n ' : ' ')
  .trim()
  .split(' ');


console.log(splitText(text))