有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?
当前回答
(function($){
$.html2text = function(html) {
if($('#scratch_pad').length === 0) {
$('<div id="lh_scratch"></div>').appendTo('body');
}
return $('#scratch_pad').html(html).text();
};
})(jQuery);
将其定义为jquery插件,并按如下方式使用:
$.html2text(htmlContent);
其他回答
这个包非常适合剥离HTML:https://www.npmjs.com/package/string-strip-html
它可以在浏览器和服务器(例如Node.js)上工作。
我想分享一下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邮件客户端都会转换这些链接,以便用户能够单击它们。
希望你觉得这很有用。
const getTextFromHtml = (t) =>
t
?.split('>')
?.map((i) => i.split('<')[0])
.filter((i) => !i.includes('=') && i.trim())
.join('');
const test = '<p>This <strong>one</strong> <em>time</em>,</p><br /><blockquote>I went to</blockquote><ul><li>band <a href="https://workingclasshistory.com" rel="noopener noreferrer" target="_blank">camp</a>…</li></ul><p>I edited this as a reviewer just to double check</p>'
getTextFromHtml(test)
// 'This onetime,I went toband camp…I edited this as a reviewer just to double check'
我只需要去掉<a>标签,并用链接的文本替换它们。
这似乎很有效。
htmlContent= htmlContent.replace(/<a.*href="(.*?)">/g, '');
htmlContent= htmlContent.replace(/<\/a>/g, '');