我想删除google apps脚本中的html格式。我目前正在搜索电子邮件并将结果打印到Google电子表格中。我想知道是否有替换text的方法。我知道正则表达式,但我认为它不适用于getBody函数。
我真的很感激这方面的一些反馈或帮助。
代码:
function Search() {
var sheet = SpreadsheetApp.getActiveSheet();
var row = 2;
// Clear existing search results
sheet.getRange(2, 1, sheet.getMaxRows() - 1, 4).clearContent();
// Which Gmail Label should be searched?
var label = sheet.getRange("F3").getValue();
// Get the Regular Expression Search Pattern
var pattern = sheet.getRange("F4").getValue();
// Retrieve all threads of the specified label
var threads = GmailApp.search("in:" + label);
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var m = 0; m < messages.length; m++) {
var msg = messages[m].getBody();
// Does the message content match the search pattern?
if (msg.search(pattern) !== -1) {
// Print the message subject
sheet.getRange(row,3).setValue(messages[m].getBody());
答案 0 :(得分:3)
替换它:
// Print the message subject
sheet.getRange(row,3).setValue(messages[m].getBody());
有了这个:
// Print the message subject
sheet.getRange(row,3).setValue(getTextFromHtml(messages[m].getBody()));
getTextFromHtml()
功能已从this answer改编而来,并添加了一些基本格式(编号和子弹列表,分段符号)的处理。
function getTextFromHtml(html) {
return getTextFromNode(Xml.parse(html, true).getElement());
}
var _itemNum; // Used to lead unordered & ordered list items.
function getTextFromNode(x) {
switch(x.toString()) {
case 'XmlText': return x.toXmlString();
case 'XmlElement':
var name = x.getName().getLocalName();
Logger.log(name);
var pre = '';
var post = '';
switch (name) {
case 'br':
case 'p':
pre = '';
post = '\n';
break;
case 'ul':
pre = '';
post = '\n';
itemNum = 0;
break;
case 'ol':
pre = '';
post = '\n';
_itemNum = 1;
break;
case 'li':
pre = '\n' + (_itemNum == 0 ? ' - ' : (' '+ _itemNum++ +'. '));
post = '';
break;
default:
pre = '';
post = '';
break;
}
return pre + x.getNodes().map(getTextFromNode).join('') + post;
default: return '';
}
}
答案 1 :(得分:1)
从这个回答:Google Apps Scripts - Extract data from gmail into a spreadsheet
只需使用getPlainBody()即可完全放弃getTextFromHTML函数;而不是getBody();。