admin 管理员组

文章数量: 1086019

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.

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.

Share Improve this question edited Jan 28, 2017 at 21:56 Oriol 289k71 gold badges457 silver badges530 bronze badges asked Jan 28, 2017 at 21:46 johnny_macjohnny_mac 1,9714 gold badges25 silver badges56 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

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>."

本文标签: javascriptDynamically add missing tags to a broken HTML stringStack Overflow