[英]How to get content inside html tags including the tags using regex in javascript?
我在下面有文字 -
how much production in batu
現在此文本顯示為一系列html
標簽。 基本上,每個單詞都包含在具有特定style
或class
的span
中。 這是它的樣子
'<span style="">how </span><span style="">much </span><span class="pink-highlight">production </span><span style="">in </span><span class="yellow-highlight">batu</span>'
現在我想從這個html
字符串中得到兩件事:樣式或 class 和跨度內的內容(沒有
)
所以我想要一個字符串中的以下信息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 </span><span style="">much </span><span class="pink-highlight">production </span><span style="">in </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.