Skip to content

Instantly share code, notes, and snippets.

@larchanka
Last active February 23, 2021 10:22
Show Gist options
  • Save larchanka/6248783e0b21d37ad02f to your computer and use it in GitHub Desktop.
Save larchanka/6248783e0b21d37ad02f to your computer and use it in GitHub Desktop.
Function converts string to HEX-color
const stringToColor = (str) => {
let hash = 0;
let color = '#';
let defaultColor = '#333333';
let i;
let value;
let strLength;
if(!str) {
return defaultColor;
}
strLength = str.length;
for (i = 0; i < strLength; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
for (i = 0; i < 3; i++) {
value = (hash >> (i * 8)) & 0xFF;
color += ('00' + value.toString(16)).substr(-2);
}
return color;
};
export default stringToColor;
@larchanka
Copy link
Author

How to use:

stringToColor('My name is...'); // returns `#034ec0`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment