【发布时间】:2013-05-17 05:45:00
【问题描述】:
我已经使用 .getBody() 从 GmailApp 中提取了一些 html,并希望返回一些 html 来过滤特定标记和内容,其中内容与数组中的任何值匹配(特别是与特定文本的链接)。查看this solution,我认为最简单的方法是使用Xml.parse() 并过滤对象,但不能超越创建XmlDocument。
例如,如果:
var html = '<div>some text then <div><a href="http://example1.com">foo</a></div> and then <span>some <a href="http://example2.com">baa</a>,and finally <a href="http://example3.com">close</a></span></div>';
和
var linksToRemove = ['baa','foo'];
我怎么能回来
var newHtml = '<div>some text then <div></div> and then <span>some ,and finally <a href="http://example3.com">close</a></span></div>';
使用
var obj = Xml.parse(html, true);
我可以得到一个要处理的对象,但一切都脱离了那里(我也考虑过只使用.replace(),但考虑到与正则表达式匹配的问题,我认为最好避免)
【问题讨论】:
-
存在不使用正则表达式解析 html 的不成文规则,但在这种情况下(这是一个简单的查找和替换),这是我会使用的方法。 XML.parse 假定格式良好的 XML 文档。尽管有最好的意图,但 HTML 通常不是。
-
@Jonathon 这样做时我遇到的问题是替换在硬编码的测试数据上没问题,但在 .getBody() html 上失败了。我的基本测试正则表达式是
html.replace(/<a\b[^>]*>(Manage your subscriptions)<\/a>/ig,"");.getBody 是否返回转义的 html? -
@Jonathon 发现 getBody() 响应中出现换行符的问题
标签: javascript xml-parsing google-apps-script