Compare hex to rgb[a] ignoring alpha
Compare hex to rgb[a] ignoring alpha
by Csaba Hellinger
JavaScript
/**
* Is a css color and a config color represent the samme RGB, ignoring alpha.
* @param {string} cssColor Actual color, querried fromm DOM, in `rgb` or `rgba` format.
* @param {string} configColor Expected color, from config in 6 or 8 digit hex format.
* @returns {boolean} True if the colors represent the same RGB.
*/
const isEqualRgb = (cssColor, configColor) => {
const cssHex = cssColor
.match(/^rgba?\((\d+), (\d+), (\d+)/)
.slice(1)
.map((x) => Number(x).toString(16).padStart(2, '0'))
.join('')
.toUpperCase();
const configHex = configColor.substring(1, 7).toUpperCase();
return cssHex === configHex;
};
const tests = [
isEqualRgb('rgba(197, 200, 13, .2)', '#C5C80D'), // ignores alpha in rgba
isEqualRgb('rgba(197, 200, 13, 1)', '#C5C80D33'), // ignores alpha in both
isEqualRgb('rgb(197, 200, 13)', '#C5C80D33'), // handles rgb too
isEqualRgb('rgb(0, 8, 14)', '#00080E'), // pads channels to 2 digits
isEqualRgb('rgb(171, 205, 239)', '#aBcDeF'), // ignores case
isEqualRgb('rgb(42, 32, 238) 0px 0px 0px 2px inset', '#2a20ee'), // ignores box shadow extra params
];
document.body.innerText = tests.every(Boolean) ? 'passed' : 'failed';