高效提取html文本内容
处理包含大量HTML标签的字符串时,快速准确地提取文本至关重要。本文介绍一种利用JavaScript正则表达式的便捷方法。
解决方案
以下JavaScript函数使用正则表达式,有效去除HTML标签,保留文本内容:
function extractText(htmlString) { return htmlString.replace(/<[^>]+>/g, ""); }
应用示例:
let html = "hello world!<br title="1<br/"></br>2"> youyou!"; let text = extractText(html); console.log(text); // 输出:hello world! youyou!
该正则表达式/]+>/g 匹配所有HTML标签(尖括号内的内容),并将其替换为空字符串,从而只留下纯文本。 g标志确保匹配所有出现的标签。