如何匹配html「a」標籤,只有沒有http的標籤,使用正則表達式?正則表達式匹配<a>標籤沒有http://
即匹配:
blahblah... < a href=\"somthing\" > ...blahblah
但不
blahblah... < a href=\"http://someting\" > ...blahblah
如何匹配html「a」標籤,只有沒有http的標籤,使用正則表達式?正則表達式匹配<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();
}
});
注意
If you use jQuery, then you might as well use '$("a:not([href^=http://])")' which works in IE. – 2010-09-19 21:27:54
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">
注:如果您在附加屬性,這將無法正常工作。
Updated it to match literally 'http://'. Note that browsers (at least Firefox) expands '//example.com/' to 'http://example.com/' (or https, depending on the current protocol). – Lekensteyn 2010-09-19 08:53:39
使用jQuery,你可以做一些很簡單:
links_that_doesnt_start_with_http = $("a:not([href^=http://])")
編輯:增加了://
+1 for an alternative that may do what the OP wants (they were quite vague as to the purpose). – 2010-09-18 20:33:06
'Nope. – 2010-09-18 20:34:44
@Eli可以很容易地添加'://'部分 - 該技術本質上是正確的。 – 2010-09-19 05:35:30
我解釋你的問題,你的意思是任何(大部分)絕對的URI與協議,而不僅僅是HTTP。添加到其他人的不正確的解決方案。你應該在href上做這個檢查:
if (href.slice(0, 2) !== "//" && !/^[\w-]+:\/\//.test(href)) {
// href is a relative URI without http://
}
你會在做什麼語言? – mkoistinen 2010-09-18 19:35:14
對於3.14e50th時間... *嘆息* – delnan 2010-09-18 19:39:14
匹配你正在尋找的最好方法是不要使用正則表達式。爲你的腰帶增加更多的工具。用自行車泵停止錘擊螺釘。 – 2010-09-19 08:56:49