2

I need a function to generate a CSS color based on a string with a range of min: #000000 and max: #FFFFFF. If the length or any of the characters in the input string changes, the function should return a different color (but it must always return the same color on the same string input).

For Example:

f("Reddit") ==>#FF0000

f("Smith") ==>#FFC0CB   

f("Smixh")==>#F008FF

f("Smith") ==>#FFC0CB

f("foo")==>#FF00FF

f("Reddit") ==>#FF0000

And so on. Any idea how to do that?

2
  • this depends COMPLETELY on what kind of qualities of the string that you want to affect the colour. ex. length of string means darker colour. Commented Dec 9, 2012 at 6:13
  • Are color dupes for different strings okay? Unique strings are impossible to guarantee without some rules governing the strings themselves. What's minimum/maximum characters for instance? Commented Dec 9, 2012 at 6:39

1 Answer 1

15

I'd hash the string and use the first six characters of the hex checksum as your hex color code:

function color(string) {
    return '#' + md5(string).slice(0, 6);
}

Demo: http://jsfiddle.net/4PMnA/48/

Sign up to request clarification or add additional context in comments.

2 Comments

CRC32 might be a better (faster) option than MD5.
jsfiddle demo did not work anymore (problem loading md5 lib). Fixed version: jsfiddle.net/4PMnA/48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.