簡體   English   中英

循環遍歷字符串中的html標記並將內部文本添加到數組中

[英]loop through html tags in string and add inner text to array

我有一些HTML內容保存為字符串。

我想循環遍歷該字符串中的每個標頭標簽並獲取其內部文本。

 let str = `<h1>topic 1</h1><p>desc of topic 1</p><h1>topic 2</h1><p>desc of topic 2</p>`; const innerHTMLarr = str.match(/<h1>(.*?)<\\/h1>/g).map(x => x); console.log(innerHTMLarr) 

數組返回整個標題文本,我如何獲得內部文本?

不介意使用jQuery。

map()嘗試/<\\/?h1>/g將所有出現的<h1><\\h1>替換為'' ,如下所示:

 let str = `<h1>topic 1</h1><p>desc of topic 1</p><h1>topic 2</h1><p>desc of topic 2</p>`; const innerHTMLarr = str.match(/<h1>(.*?)<\\/h1>/g).map(val => { return val.replace(/<\\/?h1>/g,''); }); console.log(innerHTMLarr) 

您可以在循環中使用exec() ,直到沒有匹配為止。

編輯:減少代碼

 let pattern = /<h1>(.*?)<\\/h1>/g; let str = `<h1>topic 1</h1><p>desc of topic 1</p><h1>topic 2</h1><p>desc of topic 2</p>`; let match; while (match = pattern.exec(str)) console.log(match[1]); 

Javascript全局匹配的解決方案應用於捕獲組

 let str = `<h1>topic 1</h1><p>desc of topic 1</p><h1>topic 2</h1><p>desc of topic 2</p>`; let regexpr = /<h1>(.*?)<\\/h1>/g; let match = regexpr.exec(str); while(match !== null) { console.log(match[1]); match = regexpr.exec(str); } 

使用jQuery,您可以通過以下方式執行此操作:

  let str = '<h1>topic 1</h1><p>desc of topic 1</p><h1>topic 2</h1><p>desc of topic 2</p>'; html = $.parseHTML( str ); innerHTMLarr = [], k=0; $.each( html, function( i, el ) { if(el.nodeName.startsWith('H')) innerHTMLarr[k++] = el.innerHTML; }); console.log(innerHTMLarr); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

暫無
暫無

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

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