Last active
December 19, 2024 11:23
-
-
Save olmokramer/82ccce673f86db7cda5e to your computer and use it in GitHub Desktop.
Regex for CSS colors: hex, rgb(a), hsl(a)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/(#([0-9a-f]{3}){1,2}|(rgba|hsla)\(\d{1,3}%?(,\s?\d{1,3}%?){2},\s?(1|0?\.\d+)\)|(rgb|hsl)\(\d{1,3}%?(,\s?\d{1,3}%?\)){2})/i |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's the regular expression I've got. It recognizes hex-colors and a few simple color functions. I'm using it in a
remarkjs
plugin to add color squares next to colors, similar to how GitHub does this:#4F82A9
.This regex doesn't recognize keywords and more advanced color functions, but for my use case I don't need that much specificity. You can extend this further by looking at what values are valid in the CSS specification.