猿问

如何使用正则表达式将 HTML / XML 拆分为仅使用 JavaScript 的兄弟姐妹?

我有一些文字:


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

我想把它分成:


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


<ol><li>First item</li><li>Second item</li><li>Third item</li></ol>

我不想拆分任何子元素,只是兄弟姐妹?


慕后森
浏览 86回答 1
1回答

潇湘沐

解析类似 X/HTML 的字符串的首选方法是使用DOMParser APIconst str = `<p>I hope that this works!</p>&nbsp; <p>Now that this is in, let's see!</p>&nbsp; <p>I hope that bold <strong>works too</strong>!</p>&nbsp; <p>Will this works</p>&nbsp; <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>&nbsp; <p>Now that this is in, let's see!</p>&nbsp; <p>I hope that bold <strong>works too</strong>!</p>&nbsp; <p>Will this works</p>&nbsp; <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);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答