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.
1 Answer
Reset to default 11Parse 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
版权声明:本文标题:javascript - Dynamically add missing tags to a broken HTML string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744087997a2531496.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论