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);
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));