繁体   English   中英

正则表达式匹配<a>不带http://的标签</a>

[英]Regular Expression to match <a> tags without http://

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

即匹配:

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

但不是

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

使用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中测试过)。

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


在同一主题上:

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

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

编辑:添加://

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

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

我正在解释你的问题,你的意思是任何(大多数)绝对URI与协议,而不仅仅是HTTP。 添加到其他人的错误解决方案。 你应该在href上做这个检查:

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

暂无
暂无

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

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