如何从 Javascript 中的 Link 中提取文本? [英] How to extract text from Link in Javascript?

查看:34
本文介绍了如何从 Javascript 中的 Link 中提取文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串:

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

如何从字符串中提取文本(即 StackOverFlow)?

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

推荐答案

不需要正则表达式:

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

实际上使用正则表达式解析 HTML 是邪恶的.虽然为您的特定情况想出一个表达式可能很容易,但它可能不适用于不同的字符串.

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.

这篇关于如何从 Javascript 中的 Link 中提取文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆