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);
添加回答
舉報