Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

95
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda