I'm trying to get access to a few substrings inside the a stylesheet's :root
selector.
So far, I've gotten the CSS, and I've successfully composed a regex that does the matching ok.
But in order to access the capture group, I've realised through some research that I need to do it iteratively in order to get all matches of a longer string:
const rootColors = document.styleSheets[0].cssRules[0].cssText;
const colorRegex = /--color-([\w]+-?[\w]+)/gi
const matches = []
do {
const match = colorRegex.exec(rootColors)
if (match && match[1]) matches.push(match[1])
matches.sort()
} while (colorRegex.exec(rootColors));
console.log(matches) // ["primary", "primary-dark", "secondary-light", "tertiary", "tertiary-dark"]
However, the loop fails to get all nine matches that I expect. The generated CSS looks as so:
:root {
--color-primary: #FF6342;
--color-primary-light: #fd9a77;
--color-primary-dark: #ff4d0f;
--color-secondary: #645DD7;
--color-secondary-light: #9488df;
--color-secondary-dark: #4730d1;
--color-tertiary: #7180AC;
--color-tertiary-light: #949bbc;
--color-tertiary-dark: #535e97;
}
I was sort of expecting the matches
array to contain all nine CSS variables with the prefix --color-
omitted.
Does the dowhile loop come with some caveats that I'm unaware of?