Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add missing tags to a broken HTML string

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.

like image 627
johnny_mac Avatar asked Jun 23 '26 14:06

johnny_mac


1 Answers

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>."
like image 189
Oriol Avatar answered Jun 26 '26 06:06

Oriol