2011-02-08 93 views
2

我试图在我通过Json响应循环时提取锚点的部分(URL,目标,文本)并且无法这样做。javascript正则表达式从锚定标记中提取锚文本,URL和目标

我发现这个问题/答案,让我95%的方式出现:

javascript regex to extract anchor text and URL from anchor tags

var input_content = "blah \ 
    <a href=\"http://yahoo.com\">Yahoo</a> \ 
    blah \ 
    <a href=\"http://google.com\">Google</a> \ 
    blah"; 

var matches = []; 

input_content.replace(/[^<]*(<a href="([^"]+)">([^<]+)<\/a>)/g, function() { 
    matches.push(Array.prototype.slice.call(arguments, 1, 4)); 
}); 

alert(matches.join("\n")); 

//Gives 

//<a href="http://yahoo.com">Yahoo</a>,http://yahoo.com,Yahoo 
//<a href="http://google.com">Google</a>,http://google.com,Google 

我一直没能修改上述正则表达式来获取目标。任何帮助,将不胜感激。

谢谢。

回答

0

我不知道你有机会获得的jQuery(这也可能是比原来的正则表达式慢),但你可以从JSON响应中提取标记字符串,敷在jQuery的,便于人类可读的处理:

$links.find('a').each(function(){ 
    var text = $(this).text(); 
    var target = $(this).attr('target'); 
    var href = $(this).attr('href'); 

    // Do whatever you were going to do 
}); 
+0

我能够利用jQuery,并做了这个诀窍,thx。 – Steve 2011-02-09 15:00:17