【发布时间】:2014-01-30 13:09:24
【问题描述】:
知道所有SO answers that warn against Regex to parse html 我有一个场景,解析器和 DOM 技巧是不可能的,需要使用正则表达式来删除具有定义文本值的标签和内容。例如在:
<div>foo bar</div
<a href="http://example.com">some text</a>
<div>foo bar foo bar</div>
我目前正在使用这个函数来解析出匹配的链接
/**
* Removes links from html text
* @param {string} html The html to be cleaned.
* @param {string} exclude The string of link text to remove.
* @returns {string} Cleaned html.
*/
function cleanBody(html, exclude){
html = html.replace(/\r?\n|\r|\t|/g, '');
var re = '<a\\b[^>]*>('+exclude+')<\\/a>';
return html.replace(new RegExp(re,'ig'),"");
}
在上面的示例中,我将传递 html 和字符串“一些文本”来删除它。这适用于我的场景,直到包含其他标记,例如
<div>foo bar</div
<a href="http://example.com"><font color="#1122cc">some text</font></a>
<div>foo bar foo bar</div>
如何改进正则表达式(或函数)以考虑额外的标记(不使用 DOM、jQuery 或其他库)?
【问题讨论】:
-
为什么 解析器和 DOM 技巧不可能?
-
如何创建一个单独的 div 元素并将其
innerHTML属性设置为字符串?这对你有用吗?你想定位什么“附加标记”? -
@MCL 我在 Google Apps 脚本中工作,它使用 JavaScript 语法但执行服务器端 developers.google.com/apps-script
-
HTML 来自哪里?我从未使用过 Google Apps 脚本,但似乎 UrlFetchApp 返回可解析的 HTML。这是example。
-
@MCL 来自电子邮件 (GmailService)。我确实考虑过使用 XML.parse 但 cmets 建议 find and replace 对于这种情况更好stackoverflow.com/questions/16687273/…
标签: javascript regex google-apps-script