[英]javascript regex match url
我想从必应搜索中获取网址。 我得到了html,当我执行此正则表达式/<h2><a href="(.*?)"/g
它给了我:
["<h2><a href="https://www.test.com/"", "<h2><a href="http://fr.wikipedia.org/wiki/Test_(informatique)"", "<h2><a href="http://www.speedtest.net/"", "<h2><a href="http://test.psychologies.com/"", "<h2><a href="http://www.thefreedictionary.com/test"", "<h2><a href="http://fr.wikipedia.org/wiki/Test"", "<h2><a href="http://www.wordreference.com/enfr/test"", "<h2><a href="http://www.sedecouvrir.fr/"", "<h2><a href="http://www.jeuxvideo.com/tests.htm"", "<h2><a href="http://en.wikipedia.org/wiki/Test""]
对于js代码,我使用了match
html.match(/<h2><a href="(.*?)"/g);
我只想要网址。 html在这里: http : //www.bing.com/search ?q= test 。 我已经搜索了一整天,我想也许我必须使用分组?
使用Array.map遍历html元素列表,然后执行给定的正则表达式以使用group获得链接。
"use strict";
var links = ['<h2><a href="https://www.test.com/"',
'<h2><a href="http://fr.wikipedia.org/wiki/Test_(informatique)"',
'<h2><a href="http://www.speedtest.net/"',
'<h2><a href="http://test.psychologies.com/"',
'<h2><a href="http://www.thefreedictionary.com/test"',
'<h2><a href="http://fr.wikipedia.org/wiki/Test"',
'<h2><a href="http://www.wordreference.com/enfr/test"',
'<h2><a href="http://www.sedecouvrir.fr/"',
'<h2><a href="http://www.jeuxvideo.com/tests.htm"',
'<h2><a href="http://en.wikipedia.org/wiki/Test"'];
var result = links.map(function (link) {
return /<h2><a href="(.*?)"/.exec(link)[1];
});
console.log(result);
那是一个数组。 您需要这样的东西。 您还需要团体。
var urls = html.map(function(str){
return str.replace(/.*href="([^"]+).*/, "$1");
});
如果这是在浏览器中完成的,则实际上无需尝试使用正则表达式。
var myNodeList= document.getElementsByTagName('a');
var i;
for (var i = 0; i < myNodeList.length; ++i) {
var anchor = myNodeList[i];
console.debug(anchor.href);
}
但是,正如注释中所暗示的那样,如果您真的想使用正则表达式,那么您所要做的就是遍历结果,就像您如何在JavaScript中用PHP的preg_match_all()匹配正则表达式如何匹配多个匹配项一样? 特别要注意以下几行:
while (match = re.exec(url)) {
params[decode(match[1])] = decode(match[2]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.