简体   繁体   中英

Remove CSS selectors and it's related properties if needed

I am trying to remove specific CSS selectors, and if there is no more selectors for a list of properties than the script removes it...

I was able to get a part of the script working: http://jsfiddle.net/jnbdz/MarRr/5/

Here is the code:

$$('button')[0].addEvent('click', function(){

var css = document.id('css').get('text');

var newCss = css.replace(/(\n|\r|\s\s)/g, "")
.replace(/(,\s*body\s*(?={)|,\s*body\s*(?=,)|body\s*,|,\s*head\s*(?={)|,\s*head\s*(?=,)|head\s*,)/gi, "")
.replace(/(body\s*(?={)|head\s*(?={))/gi, "")
.replace(/(^\{[^}]*?\}|\}\s*\{[^}]*?\})/gim, "");

document.id('cleancss').set('text', newCss);

});

The problem is that if I remove the line breaks the script I wrote wont be able to remove the properties that are not related to any selectors...

If I keep the line breaks it works...

Also, I would like to know from coders that are good with ReGex if my code is good...

Thanks a lot in advance for any help.

In the last replace you're using the multiline flag. That can't work, if you have only one line, which you do after the first replace. So lets keep the linebreaks first and remove them after the removal of the selectors.

You also can simplify the regexes a bit. Use x(?=a|b) instead of x(?=a)|x(?=b) . You also don't need the lazy match [^\}]*? .

Below is a working example. For clarity I only removed the body selector.

$$('button')[0].addEvent('click', function(){

    var css = document.id('css').get('text');

    var newCss = css
        // replace multiple tabs or spaces by one
        .replace(/( |\t)+/g, " ")
        // remove space at beginning of line
        .replace(/(^\s)/gm, "")
        // remove body in selector lists
        .replace(/(,\s*body\s*(?={|,)|body\s*,)/gi, "")
        // remove body before {
        .replace(/(body\s*(?={))/gi, "")
        // remove rules without selector
        .replace(/[\n\r]+\{[^\}]*\}/g, "")
        // remove linebreaks
        .replace(/[\n\r]+/g, "");

    document.id('cleancss').set('text', newCss);

});

You could further compress the stylesheet by removing spaces in front of { or after : and ,

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