[英]Javascript Regular Expression [Remove Events]
有誰知道一個好的正則表達式來從html中刪除事件。
例如字符串:
"<h1 onmouseover="top.location='http://www.google.com">Large Text</h1>
成為"<h1>Large Text</h1>
因此,保留了HTML標簽,但刪除了onmouseover,onmouseout,onclick等事件。
提前致謝!
怎么樣:
data.replace(/ on\w+="[^"]*"/g, '');
從評論中編輯:
這旨在一次性地在您的標記上運行。 如果您試圖在頁面執行期間動態刪除事件,則情況略有不同。 像jQuery這樣的javascript庫卻使它變得極為簡單:
$('*').unbind();
編輯:
將其限制為僅在標簽內要困難得多。 我不確定可以使用單個正則表達式來完成。 但是,如果沒有人能提出建議,這應該可以幫助您:
var matched;
do
{
matched = false;
data = data.replace(/(<[^>]+)( on\w+="[^"]*")+/g,
function(match, goodPart)
{
matched = true;
return goodPart;
});
} while(matched);
編輯:
我投稿為此編寫了一個正則表達式。 必須有某種方法可以檢查匹配的上下文,而不必實際捕獲匹配中標簽的開頭,但是我的RegEx-fu不夠強大。 這是我要提出的最優雅的解決方案:
data = data.replace(/<[^>]+/g, function(match)
{
return match.replace(/ on\w+="[^"]*"/g, '');
});
這是一種純JS方式:
function clean(html) {
function stripHTML(){
html = html.slice(0, strip) + html.slice(j);
j = strip;
strip = false;
}
function isValidTagChar(str) {
return str.match(/[a-z?\\\/!]/i);
}
var strip = false; //keeps track of index to strip from
var lastQuote = false; //keeps track of whether or not we're inside quotes and what type of quotes
for(var i=0; i<html.length; i++){
if(html[i] === "<" && html[i+1] && isValidTagChar(html[i+1])) {
i++;
//Enter element
for(var j=i; j<html.length; j++){
if(!lastQuote && html[j] === ">"){
if(strip) {
stripHTML();
}
i = j;
break;
}
if(lastQuote === html[j]){
lastQuote = false;
continue;
}
if(!lastQuote && html[j-1] === "=" && (html[j] === "'" || html[j] === '"')){
lastQuote = html[j];
}
//Find on statements
if(!lastQuote && html[j-2] === " " && html[j-1] === "o" && html[j] === "n"){
strip = j-2;
}
if(strip && html[j] === " " && !lastQuote){
stripHTML();
}
}
}
}
return html;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.