Javascript RegExp matches text between tags

I need to combine with javascript RegExp the line: bimbo999 from this tag: <a href="/game.php?village=828&amp;screen=info_player&amp;id=29956" >bimbo999</a>

The numbers from the URLs (village and id) change every time, so I need to somehow match the numbers with RegExp.

 </tr> <tr><td>Sent</td><td >Oct 22, 2011 17:00:31</td></tr> <tr> <td colspan="2" valign="top" height="160" style="border: solid 1px black; padding: 4px;"> <table width="100%"> <tr><th width="60">Supported player:</th><th> <a href="/game.php?village=828&amp;screen=info_player&amp;id=29956" >bimbo999</a></th></tr> <tr><td>Village:</td><td><a href="/game.php?village=828&amp;screen=info_village&amp;id=848" >bimbo999s village (515|520) K55</a></td></tr> <tr><td>Origin of the troops:</td><td><a href="/game.php?village=828&amp;screen=info_village&amp;id=828" >KaLa I (514|520) K55</a></td></tr> </table><br /> <h4>Units:</h4> <table class="vis"> 

I tried with this:

 var match = h.match(/Supported player:</th>(.*)<\/a><\/th></i); 

but does not work. Can you guys help me?

+8
javascript regex match
source share
2 answers

Try the following:

 /<a[^>]*>([\s\S]*?)<\/a>/ 
  • <a[^>]*> matches the open tag a
  • ([\s\S]*?) matches any characters before the closing tag as little as possible
  • <\/a> matches the closing tag

([\s\S]*?) captures the text between the tags as argument 1 in the array returned by calling exec or match .

This is really useful for finding text inside a elements, it is not incredibly safe or reliable, but if you have a large page of links and you just need their text, this will do it.


A safer way to do this without RegExp:

 function getAnchorTexts(htmlStr) { var div, anchors, i, texts; div = document.createElement('div'); div.innerHTML = htmlStr; anchors = div.getElementsByTagName('a'); texts = []; for (i = 0; i < anchors.length; i += 1) { texts.push(anchors[i].text); } return texts; } 
+22
source share

I have no experience with Regex, but I think you can use jQuery with .text() !

JQuery API -.text ()

I mean if you use:

 var hrefText = $("a").text(); 

You will receive text without using Regex!

.find("a") , and then you get a list of tags a , and then use .each() to loop in that list, then you can get the text with .text() .

Or you can use a class selector, identifier, or whatever you want!

+3
source share

All Articles