Generate a random color from string in JavaScript
📅July 26, 2021
Today we’ll show you how to generate a random color from string in JavaScript. Here we will create a rgb color based on the first character of a string using JavaScript.
- Redirect to another page in JavaScript
- Validate the value by regular expression in JavaScript
- How to Get current Date & Time in JavaScript
- Sorting an array in JavaScript
- JavaScript array methods Push, Pop, Shift and Unshift
Sometimes we need to implement a functionality where we have to create an icon based on the user name. That icon contains the background color and first character of a string. Check the following image for your reference.
function getRandomColor(name) {
// get first alphabet in upper case
const firstAlphabet = name.charAt(0).toLowerCase();
// get the ASCII code of the character
const asciiCode = firstAlphabet.charCodeAt(0);
// number that contains 3 times ASCII value of character -- unique for every alphabet
const colorNum = asciiCode.toString() + asciiCode.toString() + asciiCode.toString();
var num = Math.round(0xffffff * parseInt(colorNum));
var r = num >> 16 & 255;
var g = num >> 8 & 255;
var b = num & 255;
return {
color: 'rgb(' + r + ', ' + g + ', ' + b + ', 0.3)',
character: firstAlphabet.toUpperCase()
};
}
Call a function
getRandomColor("Code");
// output: {color: "rgb(240, 189, 193, 0.3)", character: "C"}
getRandomColor("Premix")
// output: {color: "rgb(81, 78, 16, 0.3)", character: "P"}
In the above code, we need to pass the string as a parameter and with the help of the above code we are returning the color in rgb format and the first character of the string in uppercase.
- First we have to get the first alphabet of the given string in upper case.
- Now get the ASCII code of the first character.
- Let’s create a number that contains 3 times ASCII value of character. It’s unique for every alphabet.
- At the last, use
Math.round
to create a rgb code and return it.