简体   繁体   中英

How to search specific attribute within a tag and remove it using javascript regex

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

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.

Well, try this:

To remove onclick, the regex will be:

    (<[^>]+)\s+onclick\s*=[\'"].*?[\'"]

正则表达式可视化

Debuggex Demo

The removeAttr function:

function removeAttr(html, attr) {

    return html.replace(new RegExp('(<[^>]+)\\s+' + attr + '\\s*=[\'"].*?[\'"]', 'gi'), '$1');
}

http://jsfiddle.net/rooseve/pC4aH/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM