I’m creating a custom CSS property text
, which acts as a shorthand for the color
and font-size
properties. In addition, it can accept a background-image
in place of a color
– things like gradients and url()
images. It can also have only a color
/background-image
or just a font-size
. Here’s some examples of what it looks like:
text: black;
text: 2rem;
text: black 2rem;
text: linear-gradient(to right, blue, red) 2rem;
text: url("/image.png") 2rem;
text: black xx-small;
I need a JavaScript function that can parse through a CSS document for these, and then extract the color
/background-image
and font-size
from each, so I can then use replace()
to compile to vanilla CSS in my plugin.
So far, I’ve tried using RegEx with two capturing groups to attempt to extract them. Here’s a similar RegEx that I used for another custom property, this one a shorthand for width
and height
:
/size:s*([d.]+(?:%|px|em|rem|vh|vw)?)(?:s+([d.]+(?:%|px|em|rem|vh|vw)?))?;/g
The problem with the text
property is that the first capturing group needs to identify colors, gradients, and url()s, which can get quite complicated and is unreliable.