【问题标题】:Javascript regex: remove all attributes except for href from multiple anchor tags. Can not include double quotes in regexJavascript 正则表达式:从多个锚标记中删除除 href 之外的所有属性。不能在正则表达式中包含双引号
【发布时间】:2020-08-06 06:05:38
【问题描述】:

所以我必须从多个锚标记中删除所有属性,除了 href="some value"。我使用的模板引擎允许在呈现最终结果之前运行服务器端函数,但由于某种内部原因,我无法在正则表达式中包含双引号,否则该函数会静默失败。话虽如此,让我们说我有以下 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>

这对我的目的来说很好用,但是有可能通过添加其他属性而添加,我只是不能真正将所有可能性添加到条件中。感谢您的任何意见

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    编辑:不包含双引号,而是使用 ascii 代码。

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

    然后替换do:

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

    请注意,这只适用于包含 href 的锚点。对于锚点中不包含 a href 的所有属性,请执行以下操作:

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

    【讨论】:

    • 重新阅读您的问题。重新发布,不带双引号。
    猜你喜欢
    • 2016-01-10
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 2011-08-11
    • 2014-06-06
    • 1970-01-01
    相关资源
    最近更新 更多