0

I want hexadecimal color code from username string. for long user name it is working correctly but for short name its failing. For freddie_steven it returns feddee, but for alex_steven it returns only aeee which is very short. How to fix this.

How to get valid hexadecimal color code from username to set a thumbnail background different with username.

#user-thumbnail{
    width: 100px;
    height: 100px;
    border-radius: 100%;
}

<div id='user-thumbnail'></div>

var username = 'freddie_steven';
var colorCode = '';

for(var i = 0; i<username.length; i++){
    if(username.charCodeAt(i) >= 97 && username.charCodeAt(i) <= 102)
        colorCode += username.charAt(i)
}

document.getElementById('user-thumbnail').style.background = '#' +colorCode.substr(0, 6);
4
  • What do you expect instead of aeee? Your code grabs the a, e, b, c, e and f characters from the name and puts them into a string. Commented May 17, 2022 at 9:54
  • well, we can't "fix" it if you we don't know what you're expecting.
    – I am L
    Commented May 17, 2022 at 9:56
  • I want to add characters to make valid hexadecimal color code Commented May 17, 2022 at 9:56
  • Do you want to get the same colour code for the same username? If so, can you generate a random colour and store this in a database, or do you need the colour code to be computed from the username? Commented May 17, 2022 at 10:06

1 Answer 1

1

Pick random character if the character does not match !

var username = 'alex_steven';
var colorCode = '';

var validHex = [
  'a',
  'b',
  'c',
  'd',
  'e',
  'f'
];
var randomNumber = Math.floor(Math.random() * validHex.length);

for (var i = 0; i < username.length; i++) {
  if (username.charCodeAt(i) >= 97 && username.charCodeAt(i) <= 102) {
    colorCode += username.charAt(i)
  } else {
    colorCode += validHex[randomNumber]
  }
}

console.log(colorCode.substr(0, 6));

Not the answer you're looking for? Browse other questions tagged or ask your own question.