意識到所有的SO answers that warn against Regex to parse html我有一種場景,解析器和DOM技巧是不可能的,需要使用正則表達式來刪除標記和具有定義文本的內容值。例如在:使用正則表達式從html中刪除匹配文本忽略內部鏈接標記的href鏈接
<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技巧爲什麼不可能*? – MCL
如何創建一個獨立的div元素並將它的'innerHTML'屬性設置爲字符串?這對你有用嗎?你想要瞄準什麼「額外的標記」? – MaxArt
@MCL我正在使用Google Apps腳本,該腳本使用JavaScript語法,但在服務器端執行https://developers.google.com/apps-script/ – mhawksey