簡體   English   中英

根據特定標簽將HTML字符串分成多個部分?

[英]Split HTML string into sections based on specific tag?

我有一個表示HTML代碼段的字符串,如下所示:

const bookString = "<h1>Chapter 1: The Beginning</h1>
<p>It was a dark and stormy night...</p>
<p>Tom ran up the stairs...</p>
<p>A shot rang out!</p>

<h1>Chapter 2: A Day at the Zoo</h1>
<p>The door swung open...</p>"

您明白了,這是我只希望看到h1,p,em / strong / i / b標簽的書。 (這來自Mammoth庫,該庫使用Word文檔並給我一個HTML字符串。)我想編寫一些JS,根據章節將其拆分,如下所示:

const chapters = [
  {
    title: "The Beginning",
    content: 
      "<p>It was a dark and stormy night...</p>
      <p>Tom ran up the stairs...</p>
      <p>A shot rang out!</p>"
    ]
  }
];

然后,我可以將其傳遞給電子書生成庫。

我應該使用Cheerio這樣的HTML解析庫來執行此操作嗎? 我不太清楚選擇內容,例如“對於每個h1 ,保存一個標題,然后為該h1之后的每個p ,推送到數組...”,或者我應該使用正則表達式,盡管通常的建議是不要在HTML上使用正則表達式?

一種方法是使用一系列split來對字符串進行排序並將其分成幾部分,然后進行一些清理工作,並通過映射初始的“殘破”字符串並在內部進行再次分裂以獲得(干凈的)標題來構建新的Array。和內容

 var bookString = `<h1>Chapter 1: The Beginning</h1> <p>It was a dark and stormy night...</p> <p>Tom ran up the stairs...</p> <p>A shot rang out!</p> <h1>Chapter 2: A Day at the Zoo</h1> <p>The door swung open...</p>`; var chapters = bookString.split('<h1>').filter(n => n).map(text => { var cut = text.replace(/\\n/g, '').split(': ')[1].split('</h1>'); return { title : cut[0], content : cut[1] } }); console.log(chapters); 

如果要使用Cheerio,則可以使用nextUntil()方法將所有元素最多增加到一個通過選擇器標識的元素

//get all elements until the next h1 is encountered
$('h1').nextUntil('h1')

然后,您可以使用它在h1集合上進行map()獲取每組內容,並最終創建您的對象

const chapters = $('h1').map((index,h1)=>{
  let content = $(h1).nextUntil('h1').map((index,p)=>$.html(p)).get().join('');
  return {
    title:$(h1).html(),
    content:content
  };
}).get();

復制演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM