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.
\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
The backslash in combination with a literal character can create a regex token with a special meaning. E.g. \d is a shorthand that matches a single digit from 0 to 9. Escaping a single metacharacter with a backslash works in all regular expression flavors.
The length of the hexadecimal color code should be either 6 or 3, excluding '#' symbol. For example: #abc, #ABC, #000, #FFF, #000000, #FF0000, #00FF00, #0000FF, #FFFFFF are all valid Hexadecimal color codes.
/^#[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.
Try this :
/^#([0-9a-f]{6}|[0-9a-f]{3})$/i
[0-9a-f]{6}
= 6 characters [0-9a-f]{3}
= 3 characters $
= end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With