artworkjpm
artworkjpm

Reputation: 1347

split string value but keep the line break inside new array

I want keep the line breaks after I do some logic in my string value for a textarea element. Lets say I have this string from my textarea:

"Test

Newline here"

array: ["Test\nNewline", "here"]

How can I save it to be like this: ["Test", "\n", "Newline", "here"]

My code:

let bodyText = "Test

Newline here"

let bodyTextArray = bodyText.split(/ |\n|(?=\n)/g)

Basically what is happening it it is splitting and removing the spaces and "\n". using positive lookahead isn't working, I was trying with negative look ahead with no success.

Any ideas?

Upvotes: 2

Views: 1893

Answers (3)

anubhava
anubhava

Reputation: 786289

You can use a split using this regex:

/(\n)+|\s+/

Code:

const input = `Test

Newline here`;

var arr = input.split(/(\n)+|\s+/);

console.log(arr.filter(Boolean));

Explanation:

  • /(\n)+|\s+/ splits input on 1+ newlines while capturing a single newline (to make \n available in output array after split) or 1+ whitespace
  • .filter(Boolean) removes empty or undefined entries from array

Upvotes: 0

JGNI
JGNI

Reputation: 4013

You need this

let bodyText = "Test
Newline here"
let bodyTextArray = bodyText.split(/( |\n)/)

If you put capturing () around what you are splitting on then that is added to the output

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627535

You can match those:

let bodyText = `Test

Newline here`
let bodyTextArray = bodyText.match(/^\n|\S+/gm)
console.log(bodyTextArray)

Details:

  • ^\n - start of a line and a newline
  • | - or
  • \S+ - any one or more non-whitespace chars.

To support CRLF, LF or CR line endings, use

/^(?:\r\n?|\n)|\S+/gm

where (?:\r\n?|\n) replaced \n and matches either a CR and an optional LF char, or just an LF char.

Upvotes: 4

Related Questions