Convert Hex to RGBA

后端 未结 18 972
南方客
南方客 2020-12-04 11:36

My fiddle - http://jsbin.com/pitu/1/edit

I wanted to try an easy hex to rgba conversion. Ever browser I\'ve used renders colors using rgb as default so when using th

18条回答
  •  难免孤独
    2020-12-04 12:36

    ES6 modern, RegEx free, solution with error checking and constant arrow function, that returns null for errors. If alpha is not given then the default value of one is used:

    const hexToRGB = (hex, alpha = 1) => {
        let parseString = hex;
        if (hex.startsWith('#')) {parseString = hex.slice(1, 7);}
        if (parseString.length !== 6) {return null;}
        const r = parseInt(parseString.slice(0, 2), 16);
        const g = parseInt(parseString.slice(2, 4), 16);
        const b = parseInt(parseString.slice(4, 6), 16);
        if (isNaN(r) || isNaN(g) || isNaN(b)) {return null;}
        return `rgba(${r}, ${g}, ${b}, ${alpha})`;
    };
    

    Note: It returns null for errors. You may replace {return null;} with a throw statement: {throw "Not a valid hex color!";}, but then you should call it from within try-catch:

    hexToRGB("#3454r5") => null
    hexToRGB("#345465") => rgba(52, 84, 101, 1)
    hexToRGB("#345465", 0.5) => rgba(52, 84, 101, 0.5)
    

提交回复
热议问题