Hex to RGB Color Converter - Javascript

A little javascript Hex to RGB color converter I wrote on my phone while sick in bed and bored :) Demo and source code with comments are below.

You can also check out the reverse RGB-to-Hex Conversion Tool.


Hex-to-RGB Conversion

Formatted RGB Color Value: 


This is nothing new of course. There are several of these online conversion tools already, but for a few reasons, I think this solution is worthy of taking up space on the Internet. Take a look at it with me if you’re interested:


//javascript function to convert Hex to RGB, CSS formatted
function convert(hex) {
    //check if first character is valid hex, expecting a hash symbol sometimes
    if (isNaN(parseInt(hex.charAt(0), 16))) {
        //if it is, get rid of the first character
        hex = hex.substr(1, 6);
    }
    //break the result into an array so we don't have to repeat lots of code like some of the other online tools
    var rgb = [];
    for (i = 0; i < 3; i++) {
        //convert shorthand syntax
        if (hex.length === 3) {
            rgb[i] = hex.substr(i, 1) + hex.substr(i, 1);
        } else {
            rgb[i] = hex.substr(i * 2, 2);
        }
    }
    
    //parse each element in the array into integers, and repopulate values if they're valid
    for (i = 0; i < 3; i++) {
        var x = parseInt(rgb[i], 16);
        //validates with useful feedback rather than just "NaN"
        if (isNaN(x)) {
            alert("Uh oh. That doesn't look like a valid hex string.");
            return "Sorry, I don't know what to do with that value. I'm just a browser :/";
        } else {
            rgb[i] = x;
        }
    }
    //output rgb values in a usable format
    return ("rgb(" + rgb + ")");
}

Have fun scripting…or converting..or whatever it is you do :)