• Post category:JavaScript
  • Reading time:2 mins read

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.

Why do we need it?

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.

Output - Generate a random color from string in JavaScript - Code Premix
Generate a random color from string in JavaScript – Code Premix

Function to create a random color

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

// output: {color: "rgb(240, 189, 193, 0.3)", character: "C"}

// 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.

That’s it for today.
Thank you for reading. Happy Coding!

Leave a Reply