正则表达式提取HREFS

时间:2010-06-13 16:56:09

标签: javascript regex

我正在寻找一个可以从中提取href的正则表达式:

<a href="/tr/blog.php?post=3593&user=930">

页面上有数百个链接,因此我只需要提取包含

的链接
/tr/blog.php

所以最后我应该留下一个从/ tr / blog

开始的链接列表

感谢您的帮助。这让我很困惑。

这是我目前正在使用的RegEx,但它匹配所有。

/href\s*=\s*\"*[^\">]*/ig;

3 个答案:

答案 0 :(得分:2)

您可以尝试使用href=\"(/tr/blog.php[^"]*)\"(将捕获到第1组),但一般情况下you should not use regex to parse HTML

答案 1 :(得分:0)

<body> <a href="/tr/blog.php?lol">fslk</a> 

<script>

    var anchors = document.getElementsByTagName('a'), captured = [];

    for ( var i = 0, l = anchors.length, href, r = /tr\/blog\.php/; i<l; ++i ) {
         href = this.href;
         if ( r.test( href ) ) {
             captured.push( this )
         }
    }

    // do what u want with captured links
    for ( var l = captured.length; l--; ) {
        alert( captured[l].href )
    }

</script>

</body>

答案 2 :(得分:0)

这有点晚了,但现在它是未来,你甚至不需要正则表达式:

document.querySelectorAll("a[href*='/tr/blog.php']")会为您提供包含该字符串的链接,或者您可以使用该字符串document.querySelectorAll("[href^='/tr/blog.php']")找到开始的链接。