1 回答
TA贡献1816条经验 获得超6个赞
解析类似 X/HTML 的字符串的首选方法是使用DOMParser API
const str = `<p>I hope that this works!</p>
<p>Now that this is in, let's see!</p>
<p>I hope that bold <strong>works too</strong>!</p>
<p>Will this works</p>
<ol><li>First item</li><li>Second item</li><li>Third item</li></ol>`;
const doc = new DOMParser().parseFromString(str, "text/html");
console.log(doc.body.children)
或者像这样,将 outerHTML 映射为字符串数组
const str = `<p>I hope that this works!</p>
<p>Now that this is in, let's see!</p>
<p>I hope that bold <strong>works too</strong>!</p>
<p>Will this works</p>
<ol><li>First item</li><li>Second item</li><li>Third item</li></ol>`;
const doc = new DOMParser().parseFromString(str, "text/html");
const children = doc.body.children;
const chStrArr = [...children].map(el => el.outerHTML);
console.log(chStrArr);
添加回答
举报