Create a hexadecimal colour based on a string with JavaScript
Here's an adaptation of CD Sanchez' answer that consistently returns a 6-digit colour code:
var stringToColour = function(str) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
var colour = '#';
for (var i = 0; i < 3; i++) {
var value = (hash >> (i * 8)) & 0xFF;
colour += ('00' + value.toString(16)).substr(-2);
}
return colour;
}
Usage:
stringToColour("greenish");
// -> #9bc63b
Example:
http://jsfiddle.net/sUK45/
(An alternative/simpler solution might involve returning an 'rgb(...)'-style colour code.)
I wanted similar richness in colors for HTML elements, I was surprised to find that CSS now supports hsl() colors, so a full solution for me is below:
Also see How to automatically generate N "distinct" colors? for more alternatives more similar to this.
Edit: updating based on @zei's version (with american spelling)
var stringToColor = (string, saturation = 100, lightness = 75) => {
let hash = 0;
for (let i = 0; i < string.length; i++) {
hash = string.charCodeAt(i) + ((hash << 5) - hash);
hash = hash & hash;
}
return `hsl(${(hash % 360)}, ${saturation}%, ${lightness}%)`;
}
// For the sample on stackoverflow
function colorByHashCode(value) {
return "<span style='color:" + stringToColor(value) + "'>" + value + "</span>";
}
document.body.innerHTML = [
"javascript",
"is",
"nice",
].map(colorByHashCode).join("<br/>");
span {
font-size: 50px;
font-weight: 800;
}
In HSL its Hue, Saturation, Lightness. So the hue between 0-359 will get all colors, saturation is how rich you want the color, 100% works for me. And Lightness determines the deepness, 50% is normal, 25% is dark colors, 75% is pastel. I have 30% because it fit with my color scheme best.
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)
.toString(16)
.toUpperCase();
return "00000".substring(0, 6 - c.length) + c;
}
To convert you would do:
intToRGB(hashCode(your_string))