JAVASCRIPT

Extracting Hex Color Codes

Discover how to efficiently extract all valid hex color codes (3-digit or 6-digit) from any string using JavaScript regular expressions for styling or parsing.

function extractHexColors(text) {
  const hexColorRegex = /#([a-fA-F0-9]{3}){1,2}\b/g;
  return text.match(hexColorRegex) || [];
}

// Examples:
const cssString = 'body { color: #FFF; background: #C0C0C0; border: 1px solid #333; }';
console.log(extractHexColors(cssString)); // [ '#FFF', '#C0C0C0', '#333' ]

const mixedString = 'Background is #FF00FF and border is #09C. Not a color: #XYZ.';
console.log(extractHexColors(mixedString)); // [ '#FF00FF', '#09C' ]
How it works: The `extractHexColors` function identifies and extracts all occurrences of valid hex color codes within a given string. The regular expression `/#([a-fA-F0-9]{3}){1,2}\b/g` specifically looks for a '#' symbol followed by either three or six hexadecimal characters (case-insensitive). The global flag `g` ensures that all matches are found, returning an array of all extracted hex codes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs