0

I have following string:

<a href="http://stackoverflow.com" target="_blank">StackOverFlow</a>

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

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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];

4 Comments

Can I use innerHTML on a string/var?
@user395881: No. Only DOM elements have that property.
your description was not as before, that's the reason I have received 2 down votes.
The question always was How can I extract text (i.e. StackOverFlow) from the string? I agree, the title can be misleading, but it's not the OP's fault that you got downvotes.
0

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

document.getElementById('linkID').innerHTML;

2 Comments

Ohh can't believe it took me this long to realise that! I thought the question referred to an actual link in the DOM.
I'm pretty sure you're right, having read and re-read the question about 10 times now! That plus the fact that the OP posted that comment about using innerHTML on a "string/var" on @Senad's answer.
0
window.onload = function(){
    var text = '<a href="http://stackoverflow.com" target="_blank">StackOverFlow</a>';
    var parser = null;
    if (window.DOMParser){
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(text,"text/xml");
    } else{ // Internet Explorer
        xmlDoc=new ActiveXObject("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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.