简体   繁体   English

如何从 Javascript 中的链接中提取文本?

[英]How to extract text from Link in Javascript?

I have following string:我有以下字符串:

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

How can I extract text (ie StackOverFlow) from the string?如何从字符串中提取文本(即 StackOverFlow)?

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 .实际上用正则表达式解析 HTML 是邪恶的 Although it might be easy to come up with an expression for your specific case, it might not work well for a different string.尽管为您的特定情况想出一个表达式可能很容易,但它可能不适用于不同的字符串。

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

If you can add an id to your link like so: `StackOverFlow" then you can get the text like this:如果您可以像这样向您的链接添加一个id :`StackOverFlow",那么您可以获得这样的文本:

document.getElementById('linkID').innerHTML;

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 http://www.w3schools.com/dom/dom_parser.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM