Open In App

How to convert Hex to RGBA value using JavaScript ?

Given a color hex code and the task is to convert Hex Value to RGBA value. Here are few of the mostly techniques discussed with the help of JavaScript. 

Approach 1:



Example: This example uses the approach discussed above. 

Javascript



const hexValue = '#fbafff';

function convertHexToRgbA(hexVal) {
    let ret;

    // If the hex value is valid.
    if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hexVal)) {

        // Getting the content after '#',
        // eg. 'ffffff' in case of '#ffffff'
        ret = hexVal.slice(1);

        // Splitting each character
        ret = ret.split('');

        // Checking if the length is 3
        // then make that 6
        if (ret.length == 3) {
            let ar = [];
            ar.push(ret[0]);
            ar.push(ret[0]);
            ar.push(ret[1]);
            ar.push(ret[1]);
            ar.push(ret[2]);
            ar.push(ret[2]);
            ret = ar;
        }

        // Starts with '0x'(in hexadecimal)
        ret = '0x' + ret.join('');

        // Converting the first 2 characters
        // from hexadecimal to r value
        let r = (ret >> 16) & 255;

        // Converting the second 2 characters
        // to hexadecimal to g value
        let g = (ret >> 8) & 255;

        // Converting the last 2 characters
        // to hexadecimal to b value
        let b = ret & 255;

        // Appending all of them to make
        // the RGBA value
        return 'rgba(' + [r, g, b].join(',') + ',1)';
    }
}

function myFunc() {
    console.log("The RGBA value of '"
        + hexValue + "' is '" +
        convertHexToRgbA(hexValue) + "'");
}

myFunc();
Output
The RGBA value of '#fbafff' is 'rgba(251,175,255,1)'

Approach 2:

Example: This example uses the approach discussed above. 

Javascript

const hexValue = '#fbafff';

function convertHexToRgbA(hex, a) {

    // Convert the first 2 characters to hexadecimal
    let r = parseInt(hex.substring(1, 3), 16),

        // Convert the middle 2 characters to hexadecimal
        g = parseInt(hex.substring(3, 5), 16),

        // Convert the last 2 characters to hexadecimal
        b = parseInt(hex.substring(5, 7), 16);

    // Append them all
    return "rgba(" + r + ", " + g + ", "
        + b + ", " + a + ")";
}

function myFunc() {
    console.log("The RGBA value of '"
        + hexValue + "' is '" +
        convertHexToRgbA(hexValue, 1) + "'");
}

myFunc();
Output
The RGBA value of '#fbafff' is 'rgba(251, 175, 255, 1)'
Article Tags :