JAVASCRIPT

Extracting All Hex Color Codes from a String

Discover how to efficiently find and extract all valid hexadecimal color codes (e.g., #RRGGBB, #RGB) from any given text using a regular expression in JavaScript.

function extractHexColors(text) {
  // Matches #RGB or #RRGGBB format hex codes.
  const hexColorRegex = /#([a-fA-F0-9]{3}){1,2}\b/g;
  const matches = text.match(hexColorRegex);
  return matches || []; // Return an empty array if no matches found
}

// Examples:
const cssContent = `
  .header { color: #FF0000; background: #336699; }
  .footer { color: #f0f; border-color: #ABC; }
  /* Not a color: #XYZ */
`;
console.log(extractHexColors(cssContent));
// Expected: ["#FF0000", "#336699", "#f0f", "#ABC"]

const simpleText = "My favorite colors are #123456 and #abc.";
console.log(extractHexColors(simpleText));
// Expected: ["#123456", "#abc"]
How it works: The `extractHexColors` function uses a regular expression with the global flag (`g`) to find all occurrences of hexadecimal color codes within a string. The regex `/#([a-fA-F0-9]{3}){1,2}\b/` specifically looks for a hash symbol (`#`) followed by either three (`{3}`) or six (`{1,2}` which expands to 3 or 6 because `[a-fA-F0-9]` matches one character) hexadecimal characters (0-9, a-f, A-F). The `\b` ensures a word boundary, preventing partial matches within other words. The `match()` method returns an array of all matches found.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs