5

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

1 Answer 1

3

You can use

const text = "word1 word2 \ngroup of words\n";
console.log(text.match(/\n.*\n|\S+/g))

The /\n.*\n|\S+/g pattern matches multiple occurrences of

  • \n.*\n - a line feed char, then any 0 or more chars other than line break chars (as many as possible) and then a line feed
  • | - or
  • \S+ - 1 or more non-whitespace chars.

See the regex demo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.