有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?


当前回答

我认为最简单的方法就是像上面提到的那样使用正则表达式。虽然没有理由使用一堆。尝试:

stringWithHTML = stringWithHTML.replace(/<\/?[a-z][a-z0-9]*[^<>]*>/ig, "");

其他回答

我修改了Jibberboy2000的答案,加入了几种<BR/>标记格式,删除了<SCRIPT>和<STYLE>标记中的所有内容,通过删除多个换行符和空格来格式化生成的HTML,并将一些HTML编码代码转换为普通代码。经过一些测试后,您似乎可以将大部分完整网页转换为保留页面标题和内容的简单文本。

在简单示例中,

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<!--comment-->

<head>

<title>This is my title</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style>

    body {margin-top: 15px;}
    a { color: #D80C1F; font-weight:bold; text-decoration:none; }

</style>
</head>

<body>
    <center>
        This string has <i>html</i> code i want to <b>remove</b><br>
        In this line <a href="http://www.bbc.co.uk">BBC</a> with link is mentioned.<br/>Now back to &quot;normal text&quot; and stuff using &lt;html encoding&gt;                 
    </center>
</body>
</html>

变成

这是我的头衔此字符串包含我要删除的html代码在这一行中,BBC(http://www.bbc.co.uk)其中提到了链接。现在回到“普通文本”和使用

JavaScript函数和测试页面如下所示:

function convertHtmlToText() {
    var inputText = document.getElementById("input").value;
    var returnText = "" + inputText;

    //-- remove BR tags and replace them with line break
    returnText=returnText.replace(/<br>/gi, "\n");
    returnText=returnText.replace(/<br\s\/>/gi, "\n");
    returnText=returnText.replace(/<br\/>/gi, "\n");

    //-- remove P and A tags but preserve what's inside of them
    returnText=returnText.replace(/<p.*>/gi, "\n");
    returnText=returnText.replace(/<a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 ($1)");

    //-- remove all inside SCRIPT and STYLE tags
    returnText=returnText.replace(/<script.*>[\w\W]{1,}(.*?)[\w\W]{1,}<\/script>/gi, "");
    returnText=returnText.replace(/<style.*>[\w\W]{1,}(.*?)[\w\W]{1,}<\/style>/gi, "");
    //-- remove all else
    returnText=returnText.replace(/<(?:.|\s)*?>/g, "");

    //-- get rid of more than 2 multiple line breaks:
    returnText=returnText.replace(/(?:(?:\r\n|\r|\n)\s*){2,}/gim, "\n\n");

    //-- get rid of more than 2 spaces:
    returnText = returnText.replace(/ +(?= )/g,'');

    //-- get rid of html-encoded characters:
    returnText=returnText.replace(/&nbsp;/gi," ");
    returnText=returnText.replace(/&amp;/gi,"&");
    returnText=returnText.replace(/&quot;/gi,'"');
    returnText=returnText.replace(/&lt;/gi,'<');
    returnText=returnText.replace(/&gt;/gi,'>');

    //-- return
    document.getElementById("output").value = returnText;
}

它与此HTML一起使用:

<textarea id="input" style="width: 400px; height: 300px;"></textarea><br />
<button onclick="convertHtmlToText()">CONVERT</button><br />
<textarea id="output" style="width: 400px; height: 300px;"></textarea><br />
function strip_html_tags(str)
{
   if ((str===null) || (str===''))
       return false;
  else
   str = str.toString();
  return str.replace(/<[^>]*>/g, '');
}

最简单的方法:

jQuery(html).text();

它从html字符串中检索所有文本。

用jQuery剥离html的一种更安全的方法是,首先使用jQuery.parseHTML创建DOM,忽略任何脚本,然后让jQuery构建元素,然后仅检索文本。

function stripHtml(unsafe) {
    return $($.parseHTML(unsafe)).text();
}

可以安全地从以下位置剥离html:

<img src="unknown.gif" onerror="console.log('running injections');">

以及其他漏洞。

nJoy!

一个非常好的库是净化html,它是一个纯JavaScript函数,可以在任何环境中使用。

我的案例是React Native,我需要从给定文本中删除所有HTML标记。所以我创建了这个包装函数:

import sanitizer from 'sanitize-html';

const textSanitizer = (textWithHTML: string): string =>
  sanitizer(textWithHTML, {
    allowedTags: [],
  });

export default textSanitizer;

现在,通过使用textSanitizer,我可以获得纯文本内容。