Reputation: 1816
Basically I have this kind of tag (just for example)
<div type="text" onclick="event();" onblur="event();">this div has onclick and onblur functions</div>
and I want to remove some attributes to that tag using a reference variable.
var refAttribs = ['onclick', 'onblur'];
So it should strip out all attributes from refAttribs
.
Be careful not to strip out the content of the div. Because it also contains a string from the refAttribs
variable.
How do I get rid of them using a regex? Thanks in advance
Upvotes: 0
Views: 129
Reputation: 5340
Well, try this:
To remove onclick, the regex will be:
(<[^>]+)\s+onclick\s*=[\'"].*?[\'"]
The removeAttr function:
function removeAttr(html, attr) {
return html.replace(new RegExp('(<[^>]+)\\s+' + attr + '\\s*=[\'"].*?[\'"]', 'gi'), '$1');
}
http://jsfiddle.net/rooseve/pC4aH/1/
Upvotes: 1
Reputation: 301
As you've stated the tag is a string then you could santise it with the following javascript.
var refAttribs = ['onclick', 'onblur'];
function remove(tagToClean)
{
var result = tagToClean;
for(var i=0; i<refAttribs.length; i++)
{
regex = new RegExp(refAttribs[i] + "=\"[a-zA-Z\(\);]*?\"", "g");
result = result.replace(regex, "");
}
return result;
}
You can call the method by passing in your string.
remove('<div type="text" onclick="event();" onblur="event();">this div has onclick and onblur functions</div>');
I'm not 100% sure what you're trying to do here. Are you trying to modify the DOM? If so you will need to modify the method to accept a handle to a DOM node. A little more information would help.
Upvotes: 2