Files
freecodecamp--freecodecamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6821ebfd237de8297eaee799.md
T
wehub-resource-sync dde272c4b8
i18n - Build Validation / Validate i18n Builds (24) (push) Has been cancelled
CI - Node.js / Lint (24) (push) Has been cancelled
CI - Node.js / Build (24) (push) Has been cancelled
CI - Node.js / Test (24) (push) Has been cancelled
CI - Node.js / Test - Upcoming Changes (24) (push) Has been cancelled
CI - Node.js / Test - i18n (italian, 24) (push) Has been cancelled
CI - Node.js / Test - i18n (portuguese, 24) (push) Has been cancelled
CD - Docker - GHCR Images / Build and Push Images (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 11:55:53 +08:00

1.3 KiB

id, title, challengeType, dashedName
id title challengeType dashedName
6821ebfd237de8297eaee799 Challenge 23: RGB to Hex 28 challenge-23

--description--

Given a CSS rgb(r, g, b) color string, return its hexadecimal equivalent.

Here are some example outputs for a given input:

Input Output
"rgb(255, 255, 255)" "#ffffff"
"rgb(1, 2, 3)" "#010203"
  • Make any letters lowercase.
  • Return a # followed by six characters. Don't use any shorthand values.

--hints--

rgbToHex("rgb(255, 255, 255)") should return "#ffffff".

assert.equal(rgbToHex("rgb(255, 255, 255)"), "#ffffff");

rgbToHex("rgb(1, 11, 111)") should return "#010b6f".

assert.equal(rgbToHex("rgb(1, 11, 111)"), "#010b6f");

rgbToHex("rgb(173, 216, 230)") should return "#add8e6".

assert.equal(rgbToHex("rgb(173, 216, 230)"), "#add8e6");

rgbToHex("rgb(79, 123, 201)") should return "#4f7bc9".

assert.equal(rgbToHex("rgb(79, 123, 201)"), "#4f7bc9");

--seed--

--seed-contents--

function rgbToHex(rgb) {

  return rgb;
}

--solutions--

function rgbToHex(rgb) {
  const match = rgb.match(/\d+/g);
  const [r, g, b] = match.map(num =>
    Math.max(0, Math.min(255, parseInt(num)))
      .toString(16)
      .padStart(2, '0')
  );

  return `#${r}${g}${b}`;
}