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

140
Vistas
Split a string in javascript

I need to split a string according to the next idea:

const strin = 'test <br><span>test</span>  <div>aa</div>8'.split(/<\ *>/i)
console.log(strin)

So, the expected output is next: ['test','<br>', '<span>test</span>', '<div>aa</div>', '8']

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

As @sebastian-simon mentioned, "split" HTML with only regular expression is impossible. The best solution is use a real HTML parser (already shipped with your browser, if you are using Node.js, you can use JSDOM).

var str = 'test <br><span>test</span> <fake></fake> <div><p>aa</p></div>8';
var container = document.createElement("div");
container.innerHTML = str; // use a HTML element to parse HTML

// If you need to work with nested tag, you should traverse childNodes and their childNodes by yourself

// childNodes included TextNode, children not.
// [...container.childNodes] convert container.childNodes to a normal array
// so we can .map over it
var elmList = [...container.childNodes];
var tags = elmList
  // if elm is a TextNode, elm.outerHTML is undefined
  // then we use elm.textContent instead
  .map(elm => elm.outerHTML ?? elm.textContent)
  .map(elm => elm.trim()) // remove whitespaces
  .filter(elm => elm); // remove empty items
console.log(tags)
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