Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!