Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract inner text from anchor tag string using a regular expression in JavaScript

I am new to angular js . I have regex which gets all the anchor tags. My reg ex is

/<a[^>]*>([^<]+)<\/a>/g

And I am using the match function here like ,

var str =  '<a href="mailto:[email protected]" style="color:inherit;text-decoration:inherit">[email protected]</a>'

So Now I am using the code like

var value = str.match(/<a[^>]*>([^<]+)<\/a>/g);

So, Here I am expecting the output to be [email protected] , But I am getting the exact same string as a input string . can any one please help me with this ? Thanks in advance.

like image 524
ganesh kaspate Avatar asked Nov 08 '22 12:11

ganesh kaspate


1 Answers

Why are you trying to reinvent the wheel?

You are trying to parse the HTML string with a regex it will be a very complicated task, just use DOM or jQuery to get the links contents, they are made for this.

  • Put the HTML string as the HTML of a jQuery/DOM element.

  • Then fetch this created DOM element to get all the a elements inside it and return their contents in an array.

This is how should be your code:

var str = '<a href="mailto:[email protected]" style="color:inherit;text-decoration:inherit">[email protected]</a>';

var results = [];
$("<div></div>").html(str).find("a").each(function(l) {
  results.push($(this).text());
});

Demo:

var str = '<a href="mailto:[email protected]" style="color:inherit;text-decoration:inherit">[email protected]</a>';

var results = [];
$("<div></div>").html(str).find("a").each(function(l) {
  results.push($(this).text());
});
console.log(results);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 171
cнŝdk Avatar answered Nov 14 '22 23:11

cнŝdk