2

how to convert rgb color to color name string in javascript

 let btn = document.querySelector("#demo");
         let css = getComputedStyle(btn);
           console.log(css.color);

output is in rgb value rgb (255,0,0)

4
  • 2
    What is "color name string"? The name of the color? The HEX code? Commented Sep 11, 2021 at 9:23
  • I'm guessing this? Commented Sep 11, 2021 at 9:44
  • like o/p is in rgb(255,0,0) but i want in color string name like red,green,blue but not rgb(255,0,0),rgb(0,255,0),rgb(0,0,255). Commented Sep 11, 2021 at 11:49
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented Sep 17, 2021 at 11:45

1 Answer 1

1

You need to convert the RGB string to a hex value, and then you can compare it against a list like this of HTML color names.

const colors={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff"};

// Pass in the string
function toHex(rgb) {

  // Grab the numbers
  const match = rgb.match(/\d+/g);

  // `map` over each number and return its hex
  // equivalent making sure to `join` the array up
  // and attaching a `#` to the beginning of the string 
  return `#${match.map(color => {
    const hex = Number(color).toString(16);
    return hex.length === 1 ? `0${hex}` : hex;
  }).join('')}`;
}

// Now just iterate over the colors object and return the
// key from the property where the value matches the hex value
function findColor(hex) {
  const pair = Object.entries(colors).find(([key, value]) => {
    return value === hex;
  });
  return pair[0];
}

const hex1 = toHex('rgb(255, 228, 196)');
console.log(findColor(hex1));

const hex2 = toHex('rgb(127, 255, 212)');
console.log(findColor(hex2));

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

Comments

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.