views:

72

answers:

1

Hi, does anyone know of a good regular expression to remove events from html.

For example the string:
"<h1 onmouseover="top.location='http://www.google.com"&gt;Large Text</h1> Becomes "<h1>Large Text</h1>
So HTML tags are preserved but events like onmouseover, onmouseout, onclick, etc. are removed.

Thanks in Advance!

+2  A: 

How about:

data.replace(/ on\w+="[^"]*"/g, '');

Edit from the comments:

This is intended to be run on your markup as a one time thing. If you're trying to remove events dynamically during the execution of the page, that's a slightly different story. A javascript library like jQuery makes it extremely easy, though:

$('*').unbind();

Edit:

Restricting this to only within tags is a lot harder. I'm not confident it can be done with a single regex expression. However, this should get you by if no one can come up with one:

var matched;

do
{
    matched = false;
    data = data.replace(/(<[^>]+)( on\w+="[^"]*")+/g,
        function(match, goodPart)
        { 
            matched = true;
            return goodPart;
        });
} while(matched);

Edit:

I surrender at writing a single regex for this. There must be some way to check the context of a match without actually capturing the beginning of the tag in your match, but my RegEx-fu is not strong enough. This is the most elegant solution I'm going to come up with:

data = data.replace(/<[^>]+/g, function(match)
{
    return match.replace(/ on\w+="[^"]*"/g, '');
});
Ian Henry
very good answer. Just a feedback for james that it wont remove events on html that have been placed unobtrusively and also it wont remove some of the click events triggered through href='javascript:function()'
sushil bharwani
Thank you for answering Ian. I am just replacing raw html, so the regex looks good. However, is there a way to specify it so that it matches only if the string is inside a tag? currently the regex would replace "onclick events can be written as onclick="something" " to "onclick events can be written as ". Any ideas? Thanks
James Cal
I appreciate the effort! I think your final attempt will work perfectly for me. Thank you :)
James Cal