簡體   English   中英

如何獲取 html 標簽內的內容,包括在 javascript 中使用正則表達式的標簽?

[英]How to get content inside html tags including the tags using regex in javascript?

我在下面有文字 -

how  much  production  in  batu

現在此文本顯示為一系列html標簽。 基本上,每個單詞都包含在具有特定styleclassspan中。 這是它的樣子

'<span style="">how &nbsp;</span><span style="">much &nbsp;</span><span class="pink-highlight">production &nbsp;</span><span style="">in &nbsp;</span><span class="yellow-highlight">batu</span>'

現在我想從這個html字符串中得到兩件事:樣式或 class 和跨度內的內容(沒有&nbsp;

所以我想要一個字符串中的以下信息array

[["", "how"], ["", "much"], ["pink-highlight", "production"], ["", "in"], ["yellow-highlight", "batu"]]

現在這可以使用regex輕松完成。 但我並不精通regex 我能想到的模式

<span>(.*?)</span>

但它只會找出span內的內容,甚至在這種情況下都不起作用,因為每個span都有一個style標簽或一個 class。

那么在這種情況下,什么regex最適合獲得所需的結果呢?

使用 reg exp 可能會因匹配 HTML 而失敗。 將其解析為 HTML 並獲取數據非常容易。

 var html = '<span style="">how &nbsp;</span><span style="">much &nbsp;</span><span class="pink-highlight">production &nbsp;</span><span style="">in &nbsp;</span><span class="yellow-highlight">batu</span>' var temp = document.createElement('div') temp.innerHTML = html var data = Array.from(temp.querySelectorAll('span')).map(span => ([ span.getAttribute("style") || span.getAttribute("class") || '', span.textContent.trim() ]) ) console.log(data)

我將提供一個簡單的正則表達式。 實際上,我只是添加了另外 2 個選項。

(<span>(.*?)<\/span>)|(<span style=".*?">(.*?)<\/span>)|(<span class=".*?">(.*?)<\/span>)

暫無
暫無

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

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