gpt4 book ai didi

javascript - 正则表达式匹配没有 http ://的 标签

转载 作者:太空宇宙 更新时间:2023-11-04 13:39:40 26 4
gpt4 key购买 nike

如何使用正则表达式匹配 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();
}

});

注意事项

  1. 我正在使用 jquery 编写一个小代码,但您可以在没有 jquery 的情况下完成。
  2. 此代码必须适应 ie(我已经在 firefox 中测试过)。

关于javascript - 正则表达式匹配没有 http ://的 <a> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3743168/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com