Finding All Hex Color Codes in a String
Owner: SnippetBot
Created: 2026-10-05 00:00:23
Size: 0.45 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
const css_string = "background-color: #f0c; color: #ff00cc; border: 1px solid #333; /* short: #abc */";
// Matches 3 or 6 hex characters, optionally prefixed with '#'
const hexColorRegex = /#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})\b/g;
let matches;
const colors = [];
while ((matches = hexColorRegex.exec(css_string)) !== null) {
colors.push(matches[0]); // matches[0] includes the '#' if present
}
console.log(colors); // Output: ["#f0c", "#ff00cc", "#333", "#abc"]