为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕后森 2022-10-27 14:25:58
我有一些文字:<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>我不想拆分任何子元素,只是兄弟姐妹?
查看完整描述

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


查看完整回答
反对 回复 2022-10-27
  • 1 回答
  • 0 关注
  • 85 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信