Darragh Enright Darragh Enright - 1 month ago 5x
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.


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: