JAVASCRIPT
Extract All Hexadecimal Color Codes from Text
Learn to find and extract all common hexadecimal color codes (e.g., #RRGGBB, #RGB, #AARRGGBB) from any string using a precise JavaScript regex pattern.
function extractHexColors(text) {
const hexColorRegex = /#([a-fA-F0-9]{3}){1,2}(?:[a-fA-F0-9]{2})?\b/g;
return text.match(hexColorRegex) || [];
}
// Example Usage:
const cssText = "body { background-color: #FF0000; color: #333; } .header { border: 1px solid #C0C0C0; background: #abc; }";
console.log(extractHexColors(cssText)); // ["#FF0000", "#333", "#C0C0C0", "#abc"]
const moreColors = "This text has #FFF, #000000, and #112233AA colors.";
console.log(extractHexColors(moreColors)); // ["#FFF", "#000000", "#112233AA"]
How it works: This JavaScript function utilizes a global regular expression to identify and extract all hexadecimal color codes from a given string. The regex pattern `/#([a-fA-F0-9]{3}){1,2}(?:[a-fA-F0-9]{2})?\b/g` specifically matches 3, 6, or 8-digit hex codes (with or without alpha channel), ensuring a comprehensive extraction.