Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

96
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda