JAVASCRIPT
Extracting All Hex Color Codes from a String with Regex in JavaScript
Discover how to programmatically find and extract all occurrences of hex color codes (e.g., #RRGGBB, #RGB) within a string using JavaScript regex for parsing CSS or themes.
function extractHexColors(text) {
const hexColorRegex = /#([a-f0-9]{3}){1,2}\b/gi;
return text.match(hexColorRegex);
}
const cssString = "color: #FF00FF; background: #333; border: 1px solid #abc; /* short hex */";
const colors = extractHexColors(cssString);
console.log(colors); // Output: ["#FF00FF", "#333", "#abc"]
How it works: The `extractHexColors` function in JavaScript uses a global, case-insensitive regular expression to find all instances of 3-digit or 6-digit hexadecimal color codes (prefixed with '#') within a given string. It returns an array of all matches found, useful for parsing CSS or theme data.