Reputation: 17
I have the following which detects if a color is HEX, RGB or HSL:
function detectColorFormat(color) {
if (color.startsWith('#')) {
return 'HEX';
} else if (color.startsWith('rgb')) {
return 'RGB';
} else if (color.startsWith('hsl')) {
return 'HSL';
}
}
Is there a way to achieve the same functionality without having to be so specific with the color string input?
For example, how can we make it so:
"ff0" //returns HEX
"#ff0" //returns HEX
"fffF00" // returns HEX
"250 50 10" //returns RGB
"250, 50, 10" //returns RGB
"rgb(250,50,10)" //returns RGB
"10,50%,80%" //returns HSL
Even better if this includes RGBA format also
Upvotes: 0
Views: 480
Reputation: 1
Detects the format of a given color string. This function examines the input color string to determine its format. It supports detection of HEX, RGB, and HSL color formats. The detection is based on regular expression matching against the expected patterns of each color format. If the input does not match any of the known patterns, the function returns 'Unknown'.
Param: string color. The color string to be analyzed for format detection. Returns: string. Returns the detected color format as 'HEX', 'RGB', 'HSL', or 'Unknown' if the format cannot be determined.
const detectColorFormat = (color) => {
if (/^#([0-9A-F]{3}){1,2}$/i.test(color)) {
return 'HEX';
} else if (/^rgb\((\d{1,3}%?,\s*){2}\d{1,3}%?\)$/i.test(color)) {
return 'RGB';
} else if (/^hsl\(\d{1,3},\s*\d{1,3}%,\s*\d{1,3}%\)$/i.test(color)) {
return 'HSL';
} else {
return 'Unknown';
}
};
Upvotes: 0
Reputation: 25322
Not yet. In the future you will be probably able to use CSS Typed Object Model API but it's not widely used and completely implemented even in the browsers that started to implement it.
Currently, you will have to use something similar to your approach (maybe you could have a regexp), but keep in mind you could have also named color (such as "red", for example) that are totally valid color value in CSS.
Upvotes: 1