Search code examples
javascriptregexsplitline-breaks

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?


Solution

  • 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