[英]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.