CSS Custom Property (Variable) in JS
Match CSS custom properties (variables) like `--brand-color` or `--font-size-lg`.
Try it in the JS tester →Pattern
regexJS
--[a-zA-Z][a-zA-Z0-9\-]* (flags: g)JavaScript / ECMAScript code
jsJavaScript
const re = new RegExp("--[a-zA-Z][a-zA-Z0-9\\-]*", "g");
const input = ":root { --brand-color: #10b981; --space-4: 1rem; }";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
How the pattern works
-- is the literal double-dash that prefixes every CSS custom property. [a-zA-Z] requires the next character to be a letter (digits and hyphens are allowed elsewhere but not in lead position by convention). [a-zA-Z0-9\-]* allows the rest of the name: any combination of letters, digits, and hyphens.
Examples
Input
:root { --brand-color: #10b981; --space-4: 1rem; }Matches
--brand-color--space-4
Input
var(--text-primary, #fff)Matches
--text-primary
Input
.foo { color: red; }No match
—