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

70
Visualizações
Split any html element separately using regex in JavaScript split

what I'm trying to achieve is when I split the inner contents of an element, I get each item seperate, but the html element needs to be 1 element in the split.

For example:

<p id="name1" class=""> We deliver
      <span class="color-secondary">software</span> &
      <span class="color-secondary">websites</span> for your organization<span class="color-secondary">.</span>
</p>

Like in the example above, I want to make anything inside the <span> 1 array item after splitting the inner contents of #name1.

So in other words, I want the split array to look like this:

[
 'we',
 'deliver',
 '<span class="color-secondary">software</span>',
 '&',
 '<span class="color-secondary">websites</span>'

 ... etc.
]

Currently this is what I have. But this does not work since it ignores the text inside of the html element and therefore splits it halfway through the element. I would also like it to be any html element, and not just limited to <span>.

let sentence = el.innerHTML; // el being #name1 in this case
let words = sentence.split(/\s(?=<span)/i);

How would I be able to achieve this with regex? Is this possible? Thank you for any help.

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

0

Here is a DOMParser based solution which parses the HTML and then iterates over the top node's children, pushing the HTML into the result array if the node is an element, or splitting the text on space (if it is a text element) and adding those values to the result array:

const html = `<p id="name1" class=""> We deliver
      <span class="color-secondary">software</span> &
      <span class="color-secondary">websites</span> for your organization<span class="color-secondary">.</span>
</p>`

const parser = new DOMParser();
const s = parser.parseFromString(html, 'text/html');
let result = [];
for (el of s.body.firstChild.childNodes) {
  if (el.nodeType == 3 /* TEXT_NODE */ ) {
    result = result.concat(el.nodeValue.trim().split(' ').filter(Boolean));
  } 
  else if (el.nodeType == 1 /* ELEMENT_NODE */ ) {
    result.push(el.outerHTML);
  }
}

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

Details are commented in example below

const nodeSplitter = (mainNode) => {
  let scan;
  /*
  Check if initial node has text or elements
  */
  if (mainNode.hasChildNodes) {
    scan =
      /*
      Collect all elements, text, and comments
      into an array
      */
      Array.from(mainNode.childNodes)
      /*
      If node is an element, return it...
      ...if node is text, use `.matchAll()` to
      find each word and add to array...
      .filter() any falsy values and flatten
      the array and then return it
      */
      .flatMap(node => {
        if (node.nodeType === 1) {
          return node;
        } else if (node.nodeType === 3) {
          const rgx = new RegExp(/[\w\\\-\.\]\&]+/, 'g');
          let strings = [...node.textContent.matchAll(rgx)]
            .filter(node => node).flat()
          return strings;
        } else {
          /*
          Otherwise, return empty array which is 
          basically nothing since .flatMap() 
          flattens an array as default
          */
          return [];
        }
      });
  } else {
    // Return if mainNode is empty
    return;
  }
  // return results
  return scan;
}

const main = document.getElementById('name1');
console.log(nodeSplitter(main));
<p id="name1" class=""> We deliver
  <span class="color-secondary">software</span> &
  <span class="color-secondary">websites</span> for your organization
  <span class="color-secondary">.</span>
</p>

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