Converting RGB to Hex using Lodash

You have: a string that looks like this 'rgb(255, 0, 255)'

You want: the hex code for it '#ff00ff' as a string

You must use: Lodash

const rgbToHex = (rgb: string) => {
  const nums = _.words(rgb, /[0-9]+/g); // remove leading "rgb" and parens
  const hex = _.map(nums, (num: string) => {
    const as16 = _.parseInt(num).toString(16);
    return `${_.size(as16) === 1 ? '0' : ''}${as16}`;
  });
  return `#${hex.join('')}`;
};

I wrote this but ended up not needing it and didn’t have the heart to just delete it.

Hope it helps someone!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.