[英]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.