Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript for extracting anchor text from anchor tag

need help in the following.

In javascript, need to pass a input

as eg:

str="<a href=www.google.com>Google</a>"; // this is for example actual input vary
// str is passed as parameter for javascript function

The output should retrieve as 'Google'.

I have regex in java and it is working fine in it.

String regex = "< a [ ^ > ] * > ( . * ? ) < / a > ";
Pattern p = Pattern.compile(regex, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);

but in javascript it is not working.

how can I do this in Javascript. Can anyone provide me help for javascript implementation.

like image 302
Manushi Avatar asked Sep 21 '25 10:09

Manushi


1 Answers

I dont think you would like to use Regex for this. You may try simply like this:-

<a id="myLink" href="http://www.google.com">Google</a>

    var anchor = document.getElementById("myLink");

    alert(anchor.getAttribute("href")); // Extract link

    alert(anchor.innerHTML); // Extract Text

Sample DEMO

EDIT:-(As rightly commented by Patrick Evans)

var str = "<a href=www.google.com>Google</a>";
var str1 = document.createElement('str1');
str1.innerHTML = str;
alert(str1.textContent);
alert( str1.innerText);

Sample DEMO

like image 150
Rahul Tripathi Avatar answered Sep 23 '25 08:09

Rahul Tripathi