I'm trying to create a dynamic css theme and in order to do that I need to extract all css variables from a string, collected from a stylesheet record. And then replace the existing values of the root variables with the ones returned from the stylesheet.
I'm mainly a CSS guy and my javascript knowledge and/or regex knowledge isn't super great. My coworker is already on holiday leave so I thought I'd ask this wonderful community :)
The stylesheet has contents that look something like this:
// ****************************
// DYNAMIC STYLESHEET THEME
// ****************************
:root {
--var-body-bg: red;
--var-text-color: green;
--var-button-primary: orange;
}
So, I need each variable because I plan to run them through this function that essentially replaces the values:
document.documentElement.style.setProperty('--var-body-bg', 'red');
I'm not even sure it'll work, but in order to even get started, I have to figure out a way to extract these values from the string.
Edit: Found a short snippet :)
var parseCssRules = function (cssText) {
var tokenizer = /\s*([a-z\-]+)\s*:\s*((?:[^;]*url\(.*?\)[^;]*|[^;]*)*)\s*(?:;|$)/gi,
obj = {},
token;
while ( (token=tokenizer.exec(cssText)) ) {
obj[token[1].toLowerCase()] = token[2];
}
return obj;
};