有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?
当前回答
myString.replace(/<[^>]*>?/gm, '');
其他回答
我认为最简单的方法就是像上面提到的那样使用正则表达式。虽然没有理由使用一堆。尝试:
stringWithHTML = stringWithHTML.replace(/<\/?[a-z][a-z0-9]*[^<>]*>/ig, "");
我想分享一下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邮件客户端都会转换这些链接,以便用户能够单击它们。
希望你觉得这很有用。
下面的代码允许您保留一些html标记,同时剥离所有其他标记
function strip_tags(input, allowed) {
allowed = (((allowed || '') + '')
.toLowerCase()
.match(/<[a-z][a-z0-9]*>/g) || [])
.join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '')
.replace(tags, function($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
});
}
一个非常好的库是净化html,它是一个纯JavaScript函数,可以在任何环境中使用。
我的案例是React Native,我需要从给定文本中删除所有HTML标记。所以我创建了这个包装函数:
import sanitizer from 'sanitize-html';
const textSanitizer = (textWithHTML: string): string =>
sanitizer(textWithHTML, {
allowedTags: [],
});
export default textSanitizer;
现在,通过使用textSanitizer,我可以获得纯文本内容。