如何使用正则表达式匹配 html 的“a”标签,只有没有 http 的标签?
即匹配:
blahblah... < a href=\"somthing\" > ...blahblah
但不是
blahblah... < a href=\"http://someting\" > ...blahblah
使用 DOMParser 更容易和 XPath ,不是正则表达式。
请参阅我在 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();
}
});
注意事项
- 我正在使用 jquery 编写一个小代码,但您可以在没有 jquery 的情况下完成。
- 此代码必须适应 ie(我已经在 firefox 中测试过)。
我是一名优秀的程序员,十分优秀!