Generate a Hex Color Code from random String
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.
