【问题标题】:Removing html tags and content where tag content matches an array of values using Xml.parse()使用 Xml.parse() 删除标记内容与值数组匹配的 html 标记和内容
【发布时间】: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(/&lt;a\b[^&gt;]*&gt;(Manage your subscriptions)&lt;\/a&gt;/ig,""); .getBody 是否返回转义的 html?
  • @Jonathon 发现 getBody() 响应中出现换行符的问题

标签: javascript xml-parsing google-apps-script


【解决方案1】:

以下建议选择尝试使用正则表达式

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 = cleanBody(html, linksToRemove);

/**
 * Removes links from html text
 * @param {string} html The html to be cleaned.
 * @param {array} exclude The array of link text to remove.
 * @returns {string} Cleaned html.
 */
function cleanBody(html, exclude) {
    html = html.replace(/\r?\n|\r|\t/g, ''); // used to remove breaks and tabs
    var re = '<a\\b[^>]*>(' + exclude.join('|') + ')<\\/a>';
    return html.replace(new RegExp(re, 'ig'), "");
}

http://jsfiddle.net/HdsPU/测试

【讨论】:

  • 如果您对某种格式有特定需求,但您或多或少知道或仍能更好地控制,那么 regex 可以很好地工作。如果您正在寻找构建浏览器,那将是最糟糕的做事方式之一:D
猜你喜欢
  • 2019-07-09
  • 2021-06-29
  • 1970-01-01
  • 2021-06-21
  • 1970-01-01
  • 2021-10-14
  • 1970-01-01
  • 1970-01-01
  • 2011-06-05
相关资源
最近更新 更多