Convert hex to RGB and RGB to hex in JavaScript
Intermediate · 4 min read
Colors on the web are often written as hex codes like #008751, the green of the Nigerian flag. Design tools, CSS files and brand guides all use them. But when you want to lighten a color, mix two, or check contrast, you need the three numbers behind the code: how much red, green and blue.
In this tutorial you will write hexToRgb, which turns #008751 into [0, 135, 81], and rgbToHex, which turns the numbers back into a code. You'll support the short form #0b0, keep values in range, and reject anything that isn't a color. You need to know strings and arrays. Hexadecimal is explained from scratch below.
What hexadecimal means
Everyday numbers are base 10: ten digits, 0 to 9. Hexadecimal (hex) is base 16: sixteen digits, 0 to 9 and then a to f for ten to fifteen.
Two hex digits can count from 00 (0) to ff (255). The first digit counts sixteens, the second counts ones. So 87 in hex is 8 × 16 + 7 = 135.
A hex color is three of those pairs after the #: red, green, blue.
# 00 87 51
red green blue
0 135 81
Reading and writing base 16
parseInt(text, 16) reads a string as a hex number. number.toString(16) writes a number in hex.
console.log(parseInt('87', 16)); // 135
console.log(parseInt('ff', 16)); // 255
console.log((135).toString(16)); // 87
console.log((11).toString(16)); // b
The second argument to parseInt, 16, is called the radix. Always pass it. Without it, parseInt reads base 10 and stops at the first letter it doesn't understand:
console.log(parseInt('1f')); // 1
console.log(parseInt('1f', 16)); // 31
There's no error, just a wrong number, and a wrong color on the screen.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
137 A hex colour, taken apart and put back
fairTurn #008751, the green on the Nigerian flag, into its three red-green-blue numbers, and turn three numbers back into a hex string. Support the three-character shorthand, clamp values that are out of range, and return null for anything that is not a colour.
Stuck? Three hints, smallest first
- 1.
parseInt(text, 16)reads base 16; without the second argument it does not. - 2. Shorthand doubles each character:
#0b0means#00bb00. - 3. Going back,
toString(16)thenpadStart(2, '0'), because 11 must be written0b.
Step 1: split the code into three pairs
function hexToRgb(hex) {
const body = hex.startsWith('#') ? hex.slice(1) : hex;
return [0, 2, 4].map((i) => parseInt(body.slice(i, i + 2), 16));
}
console.log(hexToRgb('#008751')); // [ 0, 135, 81 ]
console.log(hexToRgb('008751')); // [ 0, 135, 81 ]
First we drop the # if there is one. Then [0, 2, 4] are the starting positions of the three pairs. map slices out each pair and reads it as hex.
Step 2: shorthand and bad input
CSS allows a three-digit shorthand: #0b0 means #00bb00. Each digit is doubled. We also want null for anything that isn't six hex digits.
function hexToRgb(hex) {
let body = hex.startsWith('#') ? hex.slice(1) : hex;
if (body.length === 3) body = body[0] + body[0] + body[1] + body[1] + body[2] + body[2];
if (!/^[0-9a-f]{6}$/i.test(body)) return null;
return [0, 2, 4].map((i) => parseInt(body.slice(i, i + 2), 16));
}
console.log(hexToRgb('#0b0')); // [ 0, 187, 0 ]
console.log(hexToRgb('#FFF')); // [ 255, 255, 255 ]
console.log(hexToRgb('#12345')); // null
console.log(hexToRgb('#gggggg')); // null
console.log(hexToRgb('white')); // null
The check is a regular expression, a pattern for text. ^ and $ mean the start and end of the string, [0-9a-f] means one hex digit, and {6} means exactly six of them. The i at the end ignores case, so FFF works too.
Step 3: back to hex, with padding
Going the other way, turn each number into hex and join them. Try it without any padding first:
const naive = (r, g, b) => '#' + r.toString(16) + g.toString(16) + b.toString(16);
console.log(naive(0, 135, 81)); // #08751
console.log(naive(0, 187, 0)); // #0bb0
0 in hex is '0', a single character, so the code comes out too short and isn't a valid color. Every channel must be exactly two digits. padStart(2, '0') adds a leading zero when needed.
Step 4: clamp and round
A channel can only be 0 to 255. When you compute colors, say by lightening one, it's easy to end up with 300 or -5 or 12.6. Bring each value into range and round it before formatting:
const channel = (v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0');
const rgbToHex = (r, g, b) => '#' + channel(r) + channel(g) + channel(b);
console.log(rgbToHex(0, 135, 81)); // #008751
console.log(rgbToHex(0, 187, 0)); // #00bb00
console.log(rgbToHex(300, -5, 12.6)); // #ff000d
console.log((300).toString(16)); // 12c
Clamping means forcing a value into a range: Math.min(255, ...) caps it at 255 and Math.max(0, ...) lifts it to at least 0. The last line shows why it matters: 300 in hex has three digits and would break the code.
Round trips now work for any full six-digit code: rgbToHex(...hexToRgb('#008751')) gives back '#008751'. The ... spreads the array into three separate arguments. A shorthand like #0b0 comes back as #00bb00, the same color written the long way.
The full solution
The answer panel has hexToRgb, channel and rgbToHex, and converts the flag green both ways. The checks cover shorthand, an optional #, upper case, padding, clamping, rejected input and the missing-radix trap. Press Run to see the output.
function hexToRgb(hex) {
let body = hex.startsWith('#') ? hex.slice(1) : hex;
if (body.length === 3) body = body[0] + body[0] + body[1] + body[1] + body[2] + body[2];
if (!/^[0-9a-f]{6}$/i.test(body)) return null;
return [0, 2, 4].map((i) => parseInt(body.slice(i, i + 2), 16));
}
const channel = (v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0');
const rgbToHex = (r, g, b) => '#' + channel(r) + channel(g) + channel(b);
const GREEN = '#008751';
console.log(GREEN, '->', hexToRgb(GREEN).join(', '));
console.log('and back ->', rgbToHex(...hexToRgb(GREEN)));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the flag green comes apart', hexToRgb(GREEN), [0, 135, 81]);
test('and goes back together', rgbToHex(0, 135, 81), GREEN);
test('shorthand doubles each digit', [hexToRgb('#0b0'), hexToRgb('#fff')], [[0, 187, 0], [255, 255, 255]]);
test('the hash is optional and the case does not matter', [hexToRgb('008751'), hexToRgb('#008751'.toUpperCase())], [[0, 135, 81], [0, 135, 81]]);
test('every channel is padded to two digits, so 11 is 0b not b', [(11).toString(16), channel(11)], ['b', '0b']);
test('out of range values are clamped and fractions rounded', rgbToHex(300, -5, 12.6), '#ff000d');
test('anything that is not a colour is rejected', [hexToRgb('#12345'), hexToRgb('#gggggg'), hexToRgb('white')], [null, null, null]);
test('parseInt without a radix reads 1f as 1 and stops', [parseInt('1f'), parseInt('1f', 16)], [1, 31]);
test('and every round trip of a full hex string returns the same string', ['#000000', '#ffffff', '#0b6e4f'].map((h) => rgbToHex(...hexToRgb(h))), ['#000000', '#ffffff', '#0b6e4f']);
Two base-16 conversions and one padding rule. parseInt(pair, 16) reads hex into a number, number.toString(16) writes it back, and the padStart(2, '0') is not cosmetic: 11 becomes 'b', and three single-character channels concatenate into a string of the wrong length that no browser will accept.
The eighth assertion is the classic. parseInt('1f') is not an error and not NaN — it reads as far as it understands and returns 1, so a missing radix produces a plausible wrong colour instead of a crash. Always pass the base. Note the two functions are not perfect inverses either: hexToRgb('#0b0') then rgbToHex gives '#00bb00', the same colour spelled the long way, which is why the round-trip assertion uses full-length inputs.
The clamp belongs in the writing direction, not the reading direction. Hex can only express 0 to 255, so a computed channel of 300 or -5 — easy to produce when lightening a colour — has to be brought into range before it is formatted, or (300).toString(16) quietly emits 12c and the string is seven characters long.
Common mistakes
- Calling
parseIntwithout 16.parseInt('1f')is 1, not 31, and nothing warns you. - Forgetting
padStart(2, '0'). Small values give one digit and the code comes out too short. - Not clamping computed values. 300 becomes
12c, and the color code is seven characters long.
Try it yourself
- Write
lighten(hex, amount)that addsamountto each channel and returns a new hex code. - Accept an eight-digit code with transparency, like
#00875180, and return four numbers. - Write
mix(hexA, hexB)that averages two colors channel by channel.