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


当前回答

如果你想保留链接和内容结构(h1、h2等),那么你应该检查TextVersionJS。你可以将它与任何HTML一起使用,尽管它是为了将HTML电子邮件转换为纯文本而创建的。

用法很简单。例如,在node.js中:

var createTextVersion = require("textversionjs");
var yourHtml = "<h1>Your HTML</h1><ul><li>goes</li><li>here.</li></ul>";

var textVersion = createTextVersion(yourHtml);

或者在浏览器中使用纯js:

<script src="textversion.js"></script>
<script>
  var yourHtml = "<h1>Your HTML</h1><ul><li>goes</li><li>here.</li></ul>";
  var textVersion = createTextVersion(yourHtml);
</script>

它也适用于require.js:

define(["textversionjs"], function(createTextVersion) {
  var yourHtml = "<h1>Your HTML</h1><ul><li>goes</li><li>here.</li></ul>";
  var textVersion = createTextVersion(yourHtml);
});

其他回答

简单的2行jquery去掉html。

 var content = "<p>checking the html source&nbsp;</p><p>&nbsp;
  </p><p>with&nbsp;</p><p>all</p><p>the html&nbsp;</p><p>content</p>";

 var text = $(content).text();//It gets you the plain text
 console.log(text);//check the data in your console

 cj("#text_area_id").val(text);//set your content to text area using text_area_id

这应该可以在任何Javascript环境(包括NodeJS)上完成工作。

    const text = `
    <html lang="en">
      <head>
        <style type="text/css">*{color:red}</style>
        <script>alert('hello')</script>
      </head>
      <body><b>This is some text</b><br/><body>
    </html>`;
    
    // Remove style tags and content
    text.replace(/<style[^>]*>.*<\/style>/gm, '')
        // Remove script tags and content
        .replace(/<script[^>]*>.*<\/script>/gm, '')
        // Remove all opening, closing and orphan HTML tags
        .replace(/<[^>]+>/gm, '')
        // Remove leading spaces and repeated CR/LF
        .replace(/([\r\n]+ +)+/gm, '');
myString.replace(/<[^>]*>?/gm, '');

将HTML转换为纯文本电子邮件,保持超链接(a href)完整

hypoxide发布的上述功能运行良好,但我所追求的是基本上转换在WebRichText编辑器(例如FCKEditor)中创建的HTML并清除所有HTML,但保留所有链接,因为我希望HTML和纯文本版本都能帮助创建STMP电子邮件的正确部分(HTML和纯文字)。

经过长时间的谷歌搜索,我和我的同事使用Javascript中的正则表达式引擎得出了这个结论:

str='this string has <i>html</i> code i want to <b>remove</b><br>Link Number 1 -><a href="http://www.bbc.co.uk">BBC</a> Link Number 1<br><p>Now back to normal text and stuff</p>
';
str=str.replace(/<br>/gi, "\n");
str=str.replace(/<p.*>/gi, "\n");
str=str.replace(/<a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 (Link->$1) ");
str=str.replace(/<(?:.|\s)*?>/g, "");

str变量的开头如下:

this string has <i>html</i> code i want to <b>remove</b><br>Link Number 1 -><a href="http://www.bbc.co.uk">BBC</a> Link Number 1<br><p>Now back to normal text and stuff</p>

然后在代码运行之后,它看起来像这样:-

this string has html code i want to remove
Link Number 1 -> BBC (Link->http://www.bbc.co.uk)  Link Number 1


Now back to normal text and stuff

正如你所看到的,所有HTML都被删除了,链接也被保留了下来,超链接文本仍然完好无损。此外,我还将<p>和<br>标记替换为\n(换行符),以便保留某种视觉格式。

更改链接格式(例如,BBC(链接->http://www.bbc.co.uk))只需编辑$2(Link->$1),其中$1是href URL/URI,$2是超链接文本。由于链接直接位于纯文本正文中,大多数SMTP邮件客户端都会转换这些链接,以便用户能够单击它们。

希望你觉得这很有用。

使用Jquery:

function stripTags() {
    return $('<p></p>').html(textToEscape).text()
}