簡體   English   中英

RegEx用於提取標簽屬性

[英]RegEx for extracting tag attributes

說,我有一個像

<body class="body-element" style="background: red;"><div class="inner">...</div></body>

我想提取body標簽的所有屬性。 至於jQuery解析忽略body標簽,我不能使用它。 那么,如何使用正則表達式呢?

我只需要從body標簽提取屬性。

使用DOMParser ,獲取.body ,然后獲取其.attributes

 var s = '<body class="body-element" style="background: red;"><div>...</div></body>'; var attrs = new DOMParser().parseFromString(s, "text/html").body.attributes; for (const a of attrs) console.log("%s = %s", a.name, a.value); 

此RegEx可以幫助您將輸入的HTML字符串分為兩組,並獲得所需的屬性:

([a-z]+)="([A-Za-z0-9_\-\:\s;]+)

如有必要,可以將其他字符添加到[A-Za-z0-9_\\-\\:\\s;]

在此處輸入圖片說明

暫無
暫無

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

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