Darragh Enright Darragh Enright - 1 year ago 99
Javascript Question

Create a hexadecimal colour based on a string with JavaScript

I want to create a function that will accept any old string (will usually be a single word) and from that somehow generate a hexadecimal value between

, so I can use it as a colour for a HTML element.

Maybe even a shorthand hex value (e.g:
) if that's less complicated. In fact, a colour from a 'web-safe' palette would be ideal.

Answer Source

Just porting over the Java from Compute hex color code for an arbitrary string to Javascript:

function hashCode(str) { // java String#hashCode
    var hash = 0;
    for (var i = 0; i < str.length; i++) {
       hash = str.charCodeAt(i) + ((hash << 5) - hash);
    return hash;

function intToRGB(i){
    var c = (i & 0x00FFFFFF)

    return "00000".substring(0, 6 - c.length) + c;

To convert you would do:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download