【问题标题】:Regex find image with attribute not wrapped in a link正则表达式查找属性未包含在链接中的图像
【发布时间】:2017-02-08 22:51:44
【问题描述】:

我正在研究一个正则表达式,如果它是真的,会进行一些字符串操作,但目前我的代码被频繁触发,所以我需要它更具体。正则表达式真的不是我的强项——我目前的正则表达式是

if(/(?!<a(.*?))<img src="(.*?[^<])" data-special="(t:).*"/.test(str)) {
    // do this code
}

我的正则表达式需要找到具有特定属性值且未被 href 包围/包裹在链接中的 img 元素。例如,我希望它捕获以下内容:

<img src="http://example.com/image.jpg" data-special="t:https://www.twitter.com" />

替换成

<a href="http://example.com/"><img src="http://example.com/image.jpg" data-special="t:https://www.twitter.com" /></a>

所以if 语句只有在存在data-special 属性的字符串中存在img 标记并且包含t: 后跟任何链接时才会为真。感谢任何帮助!

【问题讨论】:

    标签: javascript jquery regex


    【解决方案1】:

    在您的简单情况下,使用:not() 选择器和.wrap() 函数就足够了:

    $('*:not(a) &gt; img[data-special^="t:"]').wrap('&lt;a href="http://example.com/"&gt;&lt;/a&gt;');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <img src="http://example.com/image1.jpg" data-special="t:https://www.twitter.com" />
    <a href=""><img src="http://example.com/image4.jpg" data-special="t:https://www.twitter.com" /></a>
    <img src="http://example.com/image2.jpg" data-special="t:https://www.twitter.com" />
    <img src="http://example.com/image3.jpg" data-special="t:https://www.twitter.com" />

    是否可以将该 jQuery 元素检查转换为条件检查 对于我的 if 语句?所以只有在有东西的时候才输入那个 if-block 包装?

    var imgs = $('*:not(a) > img[data-special^="t:"]');
    if (imgs.length) {
        imgs.wrap('<a href="http://example.com/"></a>');
    }
    

    【讨论】:

    • 感谢您的回复。是否可以将该 jQuery 元素检查转换为我的 if 语句的条件?所以只有在有东西要包装的情况下才输入那个 if 块?
    猜你喜欢
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多