【问题标题】:Regular Expression to match <a> tags without http://正则表达式匹配没有 http:// 的 <a> 标签
【发布时间】:2010-09-18 19:33:06
【问题描述】:

如何使用正则表达式匹配html“a”标签,只匹配没有http的标签?

即匹配:

blahblah... < a href=\"somthing\" > ...blahblah

但不是

blahblah... < a href=\"http://someting\" > ...blahblah

【问题讨论】:

  • 你会用什么语言做这个?
  • 第 3.14-50 次... sigh
  • 匹配您要查找的内容的最佳方法是不使用正则表达式。在您的腰带上添加更多工具。别再用自行车打气筒敲螺丝了。

标签: javascript html regex


【解决方案1】:

使用DOMParserXPath 更容易,而不是正则表达式。

jsfiddle查看我的回复。

HTML

<body>
    <div>
        <a href='index.php'>1. index</a>
        <a href='http://www.bar.com'>2. bar</a>
        <a href='http://www.foo.com'>3. foo</a>        
        <a href='hello.php'>4. hello</a>        
    </div>
</body>

JS

$(document).ready(function() {
    var type = XPathResult.ANY_TYPE;
    var page = $("body").html();
    var doc = DOMParser().parseFromString(page, "text/xml");
    var xpath = "//a[not(starts-with(@href,'http://'))]";
    var result = doc.evaluate(xpath, doc, null, type, null);

    var node = result.iterateNext();
    while (node) {
        console.log(node); // returns links 1 and 4
        node  = result.iterateNext();        
    }

});

注意事项

  1. 我使用 jquery 来编写一个小代码,但你可以不使用 jquery。
  2. 此代码必须适用于 ie(我已在 Firefox 中测试过)。

【讨论】:

  • 如果你使用jQuery,那么你还不如使用在IE中工作的$("a:not([href^=http://])")
【解决方案2】:

您应该使用 XML 解析器而不是正则表达式。


关于同一主题:

【讨论】:

    【解决方案3】:

    使用 jquery,你可以做一些非常简单的事情:

    links_that_doesnt_start_with_http = $("a:not([href^=http://])")
    

    编辑:添加了 ://

    【讨论】:

    • +1 表示可以做 OP 想要的替代方案(他们对目的非常模糊)。
    • @Eli :// 部分可以很容易地添加 - 该技术基本上是正确的。
    【解决方案4】:

    我将您的问题解释为您的意思是任何(大部分)带有协议的绝对 URI,而不仅仅是 HTTP。添加到其他人的错误解决方案中。您应该对 href 进行此检查:

    if (href.slice(0, 2) !== "//" && !/^[\w-]+:\/\//.test(href)) {
        // href is a relative URI without http://
    }
    

    【讨论】:

      【解决方案5】:
      var html = 'Some text with a <a href="http://example.com/">link</a> and an <a href="#anchor">anchor</a>.';
      var re = /<a href="(?!http:\/\/)[^"]*">/i;
      var match = html.match(re);
      // match contains <a href="#anchor">
      

      注意:如果您有其他属性,这将不起作用。

      【讨论】:

      • 不适用于&lt;a href="http.html"&gt;&lt;a href="http:foo.html"&gt;(是的,http:... 没有明确暗示 HTTP 协议,因为如果没有,所有浏览器都会忽略“http:”部分两个斜线;http:/ 等价于 /)
      • 更新了它以匹配 http://。请注意,浏览器(至少是 Firefox)会将 //example.com/ 扩展为 http://example.com/(或 https,取决于当前协议)。
      猜你喜欢
      • 2014-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-08
      • 1970-01-01
      • 2013-06-16
      相关资源
      最近更新 更多