I need to parse CSS rules and add an !important flag to each rule. It's almost finished, but it adds !important to other things, like data: uris. I want to clean up the !important flags from the data: uri's (4th replace()), or ideally, block it from looking for rules inside CSS url( .. ) blocks (2nd replace()).
// add !important to every style
function persist(css) {
return css
.replace(/\s*!\s*important/gi, "") // remove existing !important's from all rules to simplify things
.replace(/(:.+?);/gi, "$1 !important;") // add !important to all style rules
.replace(/(@namespace.*\))\s*!important/gi, "$1") // remove !important from namespace declarations
.replace(/(data:[^\s\n]*)!important;/gi, "$1"); // remove !important from data: urls
}
Its a script for the userChrome.js firefox extension that adds a button to the Stylish extension. Adding the !important flag to a CSS rule means a webpage can't override it. Some user styles have many rules, so this enables adding them to all rules at once.
Also, sorry if this is in the wrong forum. This is a regexp problem though, not JavaScript.
feyd, sorry for not coming back to thank you sooner, that regex works great! And, using this amazing tool and some experimenting, I managed to simplify it to this:
I'm seeing weird behavior of the \n character. It seems just using \n by itself will match multiple newlines. Even weirder is that if I try to use \n* to match 0 or more newlines (to preserve the position of the closing curly brace "}"), it fails to match any newlines at all.
Nevermind, I found the solution. It was the greediness of \s* ! Adding a ? fixed it. With some more changes to handle CSS comments, here's the final regex: