简体   繁体   English

如何在谷歌应用程序脚本中将html字符串转换为没有html标签的纯文本?

[英]How to convert html string to plain text without html tags in google app script?

I'm new to google app script.我是谷歌应用程序脚本的新手。

I was trying to convert html string to plain text without html tags in google app script using the reference in this question.我试图使用此问题中的参考将 html 字符串转换为没有 html 标签的纯文本在谷歌应用程序脚本中。

However, when I try to apply it to my script, it is not working as expected.但是,当我尝试将它应用于我的脚本时,它没有按预期工作。

This is the script that I use:这是我使用的脚本:

 function toStringFromHtml(html) { html = '<div>' + html + '</div>'; html = html.replace(/<br>/g,""); var document = XmlService.parse(html); var strText = XmlService.getPrettyFormat().format(document); strText = strText.replace(/<[^>]*>/g,""); return strText; }

and this is the output:这是输出: 在此处输入图片说明

While my actual expectation is in the third column.虽然我的实际期望在第三列。

Can someone tell me what is wrong with my previous script?有人能告诉我我以前的脚本有什么问题吗?

Thank you!谢谢!

In your situation, for example, how about the following modification?例如,在您的情况下,以下修改如何?

From:从:

return strText;

To:到:

return strText.trim();

Reference:参考:

If you're running in a browser, then the easiest way is just to let the browser do it for you如果您在浏览器中运行,那么最简单的方法就是让浏览器为您完成

 function stripHtml(html) { let tmp = document.createElement("DIV"); tmp.innerHTML = html; return tmp.textContent || tmp.innerText || ""; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM