簡體   English   中英

Javascript 正則表達式:從多個錨標記中刪除除 href 之外的所有屬性。 不能在正則表達式中包含雙引號

[英]Javascript regex: remove all attributes except for href from multiple anchor tags. Can not include double quotes in regex

所以我必須從多個錨標記中刪除所有屬性,除了 href="some value"。 我使用的模板引擎允許在呈現最終結果之前運行服務器端函數,但由於某些內部原因,我無法在正則表達式中包含雙引號,否則 function 會默默地失敗。 話雖如此,讓我們說我有以下 HTML:

<p>just a bunch of text here<a data-sv-linklookup-id="https://www.somesite.com/somevalue/?i=632738&amp;ver=html5" data-sv-linklookup-type="plugins_nav_external_link" href="https://www.somesite.com/somevalue/?i=632738&amp;ver=html5" target="_blank">view it online</a> or request it through our<a data-sv-linklookup-id="5a8dad3e2f124e053ecfe720" data-sv-linklookup-type="plugins_nav_navitem_primary_main" href="https://www.somesite.com/plan-your-trip/free-visitor-guide/" target="_self" title="some title">online form</a>. a lot more text here<a data-sv-linklookup-id="5a8dad402f124e053ecfebd2" data-sv-linklookup-type="plugins_nav_navitem_primary_main" href="https://www.somesite.com/" target="_self" title="some title">some more text</a></p>

到目前為止,我已經嘗試了以下方法:

/data-sv-linklookup-id=.[^\s]*|data-sv-linklookup-type=.[^\s]*|target=.[^>]*|title=.[^>]*/g

結果是:

<p>just a bunch of text here<a   href="https://www.somesite.com/somevalue/?i=632738&amp;ver=html5" >view it online</a> or request it through our<a   href="https://www.somesite.com/plan-your-trip/free-visitor-guide/" >online form</a>. a lot more text here<a   href="https://www.somesite.com/" >some more text</a></p>

這對我的目的來說很好用,但是有可能通過添加其他屬性來添加,我只是不能真正將所有可能性添加到條件中。 感謝您的任何意見

編輯:不包括雙引號,而是使用 ascii 代碼。

https://regex101.com/r/KNMcZh/5

然后替換做:

yourString.replace(/<a.*?(href=\x22.*?\x22).*?>/g, '<a $1>');

請注意,這僅適用於包含 href 的錨點。 對於不包含 a href 的錨點的所有屬性,請執行以下操作:

yourString.replace(/<a .*?>/g, '<a>');

暫無
暫無

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

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