Hex to RGB Converter

by Siva Subramaniam

JavaScript

/* Function to convert a hex color code into RGB string */

function getRGB(rgb) {
    var i, length = rgb.length,
        output, isShort;
    if (typeof rgb == "string") {
        if (length == 4 || length == 7) {
            isShort = length - 7;
            output = "rgb(";
            for (i = 1;;) {
                if (!isShort) {
                    output += parseInt(rgb[i] + rgb[i + 1], 16);
                    i += 2;
                } else {
                    output += parseInt(rgb[i] + rgb[i], 16);
                    i++;
                }
                if (i < length) output += ",";
                else break;
            }
            output += ")";
        } else {
            console.log("I cannot convert an invalid color code");
        }
    } else {
        console.log("I guess you are looking for some other function");
    }
    return output;
}
console.log(getRGB("#333"));