Generate a Hex Color Code from random String

Shiv Kumar Ganesh
Jul 20, 2017 · 2 min read

In this particular article, we will focus our attention on generating a Hex Color Code from an Arbitrary string. This arbitrary string can be anything from a name to a randomly generated value. This comes handy in various instances for example. Color coding user cards or color coding a particular element on the page at random. Lets have a look at the code below and try to execute it as well.

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)
.toString(16)
.toUpperCase();

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

This code first generates a hash for the string and then generates the Hex Color Code. Let’s see this in action on a REPL or see below in order to make it work and check out the code as well.

If you want to see a fully working sample which uses this Example, you can have a look at the Vue.js Watchers Tutorial. That Tutorial will show you the implementation of “Generate a Hex Color Code from random String”.


Originally published at The Web Juice.

)

Shiv Kumar Ganesh

Written by

Interested in friends and am a Web Developer. Design Websites and Web Solutions in major Platforms, SEO Consultant

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade