I have a string of broken HTML. I need to search the string and add any missing opening or closing tags in JavaScript. No Regex, no jQuery. For example, I want to make a string like this:
"This <small>is <i>ONE</small> Messed up string</i>."
have proper form like this:
"This <small>is <i>ONE</i></small><i> Messed up string</i>."
Basically, the first <i> is a child of the <small> element. So I need to make sure the closing tag is placed properly and another opening tag for the misplaced original ending tag.
Parse the string, and serialize it again. There are various ways to do this.
var str = "This <small>is <i>ONE</small> Messed up string</i>.";
str = new DOMParser().parseFromString(str, "text/html").body.innerHTML;
console.log(str);//"This <small>is <i>ONE</i></small><i> Messed up string</i>."
var str = "This <small>is <i>ONE</small> Messed up string</i>.";
var el = document.implementation.createHTMLDocument().createElement('div');
el.innerHTML = str;
str = el.innerHTML;
console.log(str);//"This <small>is <i>ONE</i></small><i> Messed up string</i>."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With