Skip to content Skip to sidebar Skip to footer

How To Extract Text From Link In Javascript?

I have following string: StackOverFlow How can I extract text (i.e. StackOverFlow) from the string?

Solution 1:

No regex required:

var t_ = document.createElement('div'),
    a;
t_.innerHTML = htmlString; // <- string containing your HTML
a = t_.children[0];

var text = a.textContent || a.innerText; // W3C vs IE

Actually parsing HTML with regular expressions is evil. Although it might be easy to come up with an expression for your specific case, it might not work well for a different string.

Solution 2:

document.getElementById('link_id').innerHTML;

That was my solution before, user added more description but this is solution for current description

var s = '<a href="http://stackoverflow.com" target="_blank">StackOverFlow</a>';
var text = s.match(/<a[^\b>]+>(.+)[\<]\/a>/)[1];

Solution 3:

If you can add an id to your link like so: `StackOverFlow" then you can get the text like this:

document.getElementById('linkID').innerHTML;

Solution 4:

window.onload = function(){
    var text = '<a href="http://stackoverflow.com" target="_blank">StackOverFlow</a>';
    var parser = null;
    if (window.DOMParser){
        parser = newDOMParser();
        xmlDoc = parser.parseFromString(text,"text/xml");
    } else{ // Internet Explorer
        xmlDoc=newActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(text); 
    }
    var a = xmlDoc.childNodes[0];
    alert(a.childNodes[0].nodeValue);
}

http://www.w3schools.com/dom/dom_parser.asp

Post a Comment for "How To Extract Text From Link In Javascript?"