I have a string like this:
"word1 word2 \ngroup of words\n"
I need to split it by spaces except for the spaces that occur between 2 \n
, and preserve the \n
character. So the result would be an array like this:
[
"word1",
"word2",
"\ngroup of words\n"
]
I've found results that achieve the same thing with ,
instead of \n
, but it's not possible for me to replace it with any other character.
I'm currently using the code below, but it doesn't preserve the \n
.
input.split('\n').flatMap((s,i)=>i%2?`\n${s.trim()}\n`:s.trim().split(' ')).filter(v=>v)
Notes:
If the input string has words before \n
, there will always be a space before it, i.e. a string can contain word1 \ngroup 1\n
, but never word1\ngroup 1\n
A string can also contain multiple groups, like word1 \ngroup 1\n word2 \ngroup 2\n