Back to the lesson

Find color in the format #abc or #abcdef

Write a regexp that matches colors in the format #abc or #abcdef. That is: # followed by 3 or 6 hexadimal digits.

Usage example:

let reg = /your regexp/g;

let str = "color: #3f3; background-color: #AA00ef; and: #abcd";

alert( str.match(reg) ); // #3f3 #AA0ef

P.S. Should be exactly 3 or 6 hex digits: values like #abcd should not match.

A regexp to search 3-digit color #abc: /#[a-f0-9]{3}/i.

We can add exactly 3 more optional hex digits. We don’t need more or less. Either we have them or we don’t.

The simplest way to add them – is to append to the regexp: /#[a-f0-9]{3}([a-f0-9]{3})?/i

We can do it in a smarter way though: /#([a-f0-9]{3}){1,2}/i.

Here the regexp [a-f0-9]{3} is in parentheses to apply the quantifier {1,2} to it as a whole.

In action:

let reg = /#([a-f0-9]{3}){1,2}/gi;

let str = "color: #3f3; background-color: #AA00ef; and: #abcd";

alert( str.match(reg) ); // #3f3 #AA0ef #abc

There’s minor problem here: the pattern found #abc in #abcd. To prevent that we can add \b to the end:

let reg = /#([a-f0-9]{3}){1,2}\b/gi;

let str = "color: #3f3; background-color: #AA00ef; and: #abcd";

alert( str.match(reg) ); // #3f3 #AA0ef