简体   繁体   English

Javascript 正则表达式:从多个锚标记中删除除 href 之外的所有属性。 不能在正则表达式中包含双引号

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

So I have to strip out all attributes from multiple anchor tags, except for the href="some value".所以我必须从多个锚标记中删除所有属性,除了 href="some value"。 The templating engine that I am using allows for server-side functions to run before rendering the final result, but for some internal reason I am unable to include a double quote in the regex otherwise the function just fails silently.我使用的模板引擎允许在呈现最终结果之前运行服务器端函数,但由于某些内部原因,我无法在正则表达式中包含双引号,否则 function 会默默地失败。 So with that being said let us say that I have the following HTML:话虽如此,让我们说我有以下 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>

So far I have tried the following:到目前为止,我已经尝试了以下方法:

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

Which results in:结果是:

<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>

This works just fine for my purposes, but there is a potential that there may by other attributes added and I just can't really add all of the possibilities to the conditional.这对我的目的来说很好用,但是有可能通过添加其他属性来添加,我只是不能真正将所有可能性添加到条件中。 Thanks for any input感谢您的任何意见

Edit: does not include double quotes, uses ascii code instead.编辑:不包括双引号,而是使用 ascii 代码。

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

Then to replace do:然后替换做:

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

Note that will only work for anchors that contain an href.请注意,这仅适用于包含 href 的锚点。 To all the attributes from anchors that do not contain an a href do:对于不包含 a href 的锚点的所有属性,请执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM