Well, I’m pretty new on regex and in particular on JavaScript regexp.
I’m looking for making a regexp that match the hex color syntax (like #34ffa6)
Then I looked at the w3school page: Javascript RegExp Object
Then that’s my regexp:
/^#[0-9a-f]{6}/i
It seems to work but, if I want it to match also the “short hex color syntax” form? (like #3fa), it’s possible? I’ve tried using the character | but maybe I’m wrong with the syntax.
Advertisement
Answer
/^#[0-9a-f]{3,6}$/i
would match #abc, #abcd, #abcde, #abcdef
/^#([0-9a-f]{3}|[0-9a-f]{6})$/i
would match #abc and #abcdef but not #abcd
/^#([0-9a-f]{3}){1,2}$/i
would match #abc and #abcdef but not #abcd
/^#(?:[0-9a-f]{3}){1,2}$/i
would match #abc and #abcdef but not #abcd
Have a look at RegExp – MDN to learn more about regular expressions in javascript.