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


当前回答

const strip=(text) =>{
    return (new DOMParser()?.parseFromString(text,"text/html"))
    ?.body?.textContent
}

const value=document.getElementById("idOfEl").value

const cleanText=strip(value)

其他回答

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

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

import sanitizer from 'sanitize-html';

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

export default textSanitizer;

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

我只需要去掉<a>标签,并用链接的文本替换它们。

这似乎很有效。

htmlContent= htmlContent.replace(/<a.*href="(.*?)">/g, '');
htmlContent= htmlContent.replace(/<\/a>/g, '');

我想分享一下Shog9批准答案的编辑版本。


正如Mike Samuel在评论中指出的那样,该函数可以执行内联javascript代码。但Shog9说“让浏览器为你做……”是对的

所以…这里是我的编辑版本,使用DOMParser:

function strip(html){
   let doc = new DOMParser().parseFromString(html, 'text/html');
   return doc.body.textContent || "";
}

这里是测试内联javascript的代码:

strip("<img onerror='alert(\"could run arbitrary JS here\")' src=bogus>")

此外,它不会在解析时请求资源(如图像)

strip("Just text <img src='https://assets.rbl.ms/4155638/980x.jpg'>")

将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邮件客户端都会转换这些链接,以便用户能够单击它们。

希望你觉得这很有用。

方法1:

function cleanHTML(str){
  str.replace(/<(?<=<)(.*?)(?=>)>/g, '&lt;$1&gt;');
}

function uncleanHTML(str){
  str.replace(/&lt;(?<=&lt;)(.*?)(?=&gt;)&gt;/g, '<$1>');
}

方法2:

function cleanHTML(str){
  str.replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function uncleanHTML(str){
  str.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
}

此外,不要忘记,如果用户碰巧发布了一条数学评论(例如:1<2),您不想删除整个评论。浏览器(仅测试了chrome)不将unicode作为html标记运行。如果将所有<替换为&lt;字符串中的每一个文件,unicode都将显示<为文本,而不运行任何html。我推荐方法2。jquery也能很好地工作$('#element').text();