[英]Extracting Element from html document for android app using Jsoup
[英]Extracting the property of an HTML element using RegEx
我正在處理一些圖像延遲,並且正在尋找一種刪除 src 元素的方法。 我有一個特定的用例,我需要使用正則表達式,以便我可以在服務器端呈現結果並停止加載 src,直到我在 JS 中告訴它。
基本上我需要一種方法來可靠地替換圖像標簽中的src
。 不是值,而是實際的屬性名稱。
截至目前,我正在測試以下內容:
<img[^>]+src\\s*=\\s*['"]([^'"]+)['"][^>]*>
。
給出我的示例文本,找到整個字符串<img src="aaaa" />
。 我基本上只需要它來突出src
。 這樣我就可以 regex_replace 將src
更改為data-deferred
。
示例文本
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis bibendum lorem bibendum lectus rhoncus molestie. <img src ="aaaa" /> Maecenas ipsum justo, fermentum nec lacus in, porta consectetur metus.
這是我的 Regex101: https ://regex101.com/r/RATGgw/1/
因為我並不總是可以訪問我將不得不解析的 HTML,所以我不能只定位src
。 我需要確保在圖像標簽內的任何地方找到它時它只是src
。
知道我如何修改它以實現這一目標嗎?
編輯:
為了澄清問題,我如何使用 RegEx 才能僅在圖像標簽中找到src
屬性。
所以我找到的結果將允許我用自定義數據屬性替換src="https://"
,如data-deferred="https://"
。
您可以通過在正則表達式中使用捕獲組(括號)來將src
屬性替換為data-deferred
屬性,如下所示:
// [ $1 ][$2 ][?= a lookahead (no capture) ][global - replace all] var regex = /(<img[^>]+)(src)(?=\\s*=\\s*['"][^'"]+['"][^>]*>)/g; var text = 'Lorem ipsum. <img alt="foo" src ="aaaa" title="bar" /> Maecenas metus.'; var result = text.replace(regex, '$1data-deferred'); console.log(result); // Lorem ipsum. <img alt="foo" data-deferred ="aaaa" title="bar" /> Maecenas metus.
您想將 jQuery 用於這樣的事情:
$('img[data-deferred]').each(function(i, img){
$(img).attr('src', $(img).attr('data-deferred'))
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.