亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用正則表達式將 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 關注
  • 101 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號