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

206
Views
How to remove or close unclosed HTML in JavaScript?

Supposedly I have a string like this that will go to my HTML:

<div>Wakanda Forever</div> <span class="movie">Black Panther</span>
Movies movies movies 
<span class="movie">Spider man...

The last span tag isn't closed.

In Regular expression and JavaScript, how can I remove the unclosed <span class="movie"> from <span class="movie">Spider man... or close it with a </span> tag?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Using regular expressions to do any sort of HTML manipulation is almost always a bad idea.

My recommended solution would be to do what the browser does: Parse the string into a DOM (in a similar fuzzy, forgiving way) and then turn that DOM back into HTML.

In a browser environment, this is especially easy because you can let the browser itself do it for you, by writing the bad HTML into innerHTML of an element and then reading it back - and the browser will have fixed it for you:

const badHtml = `
<div>Wakanda Forever</div> <span class="movie">Black Panther</span>
Movies movies movies 
<span class="movie">Spider man...
`

const element = document.createElement('i')
element.innerHTML = badHtml
const result = element.innerHTML

console.log(result)

In node.js, you could instead use a library like cheerio:

import cheerio from 'cheerio'

const badHtml = `
<div>Wakanda Forever</div> <span class="movie">Black Panther</span>
Movies movies movies 
<span class="movie">Spider man...
`

const $ = cheerio.load(badHtml)
const result = $.html()

console.log(result)
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!