Regex remove some elements of the style attribute

1

I need to keep only some properties of the style attribute in tags present in a string of an html document, they will be placed in a whitelist, everything else will be removed. In the example below:

<TD class=xl76 style="BORDER-TOP: windowtext 0.5pt solid; HEIGHT: 15pt; BORDER-RIGHT: windowtext 0.5pt solid; WIDTH: 883pt; BORDER-BOTTOM: windowtext 0.5pt solid; BORDER-LEFT: windowtext 0.5pt solid; BACKGROUND-COLOR: transparent" height=20 width=1177 colSpan=25><FONT face=Calibri><STRONG>INDICADORES DO MÊS DE ABRIL DE 2016</STRONG></FONT></TD>

I would just keep the border and the background and delete the rest of the style from the column:

<TD style="BORDER-TOP: windowtext 0.5pt solid; BORDER-RIGHT: windowtext 0.5pt solid; BORDER-BOTTOM: windowtext 0.5pt solid; BORDER-LEFT: windowtext 0.5pt solid; BACKGROUND-COLOR: red"><FONT face=Calibri><STRONG>INDICADORES DO MÊS DE ABRIL DE 2016</STRONG></FONT></TD>

I can isolate the contents of style with the following regex:

/(style=")([\s\S])(")/gi

But how to remove, keep the css?

    
asked by anonymous 22.06.2016 / 20:15

2 answers

4

If this attribute is with the correct syntax, the safest is to interpret what is set and remove it by properties. By regex it seems to me half blind and it can have flaws. One suggestion:

var keepStyles = (function() {
    function getStyles(el) {
        var attr = el.getAttribute('style');
        return attr.split(';').map(function(chunk) {
            var rule = chunk.split(':').map(function(part) {
                return part.trim().toLowerCase();
            });
            return {
                type: rule[0],
                value: rule[1]
            };
        });
    }

    function setStyles(el,styles) {
        var string = styles.reduce(function(str, obj) {
            return str + [obj.type, obj.value].join(':') + ';';
        }, '');
        el.setAttribute('style', string);
    }
    return function(toKeep, el) {
        var current = getStyles(el);
        var keep = current.filter(function(obj) {
            return toKeep.indexOf(obj.type) != -1;
        });
        setStyles(el, keep);
    }
})();

So you generate a function that can receive an array with the styles to maintain ... and use like this:

keepStyles(['border-top'], document.querySelector('td'));

Example: link

    
22.06.2016 / 21:18
0

You can try removing the other styles using replace, see the example below, in javascript:

style = "color: red; background: #000; position: fixed; top:0; left: 0;";
style.replace(/color:.*?;|top:.*?;|left:.*?;/g,"");

The replace will remove: color, top and left;

    
22.06.2016 / 21:09