gpt4 book ai didi

javascript - 使用 Xml.parse() 删除标签内容与值数组匹配的 html 标签和内容

转载 作者:行者123 更新时间:2023-11-28 02:14:03 26 4
gpt4 key购买 nike

我使用 .getBody() 从 GmailApp 中提取了一些 html,并希望返回一些 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() 但考虑到与正则表达式匹配的问题,我认为最好避免)

最佳答案

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

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/ 进行测试

关于javascript - 使用 Xml.parse() 删除标签内容与值数组匹配的 html 标签和内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16687273/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com