A 3-digit hexadecimal RGB notation (#rgb
) can be converted to the 6-digit form (#rrggbb
) by replicating the digit for each color channel. For example, #fb0
expands to #ffbb00
, and so on.
There are several ways to make this conversion using JavaScript. One of the simpler ways you can achieve this is in the following way:
// ES12+ const normalizeHex = (hex) => ( (hex.length > 3) ? hex : hex.replaceAll(/(.{1})/g, '$1$1') ); console.log(normalizeHex('fb0')); // ffbb00 console.log(normalizeHex('0fc')); // 00ffcc console.log(normalizeHex('fff')); // ffffff console.log(normalizeHex('000')); // 000000
This function returns the hexadecimal value as is for values exceeding a length of three, and for all others, it uses String.prototype.replaceAll()
to duplicate value for each color channel.
Since String.prototype.replaceAll()
was added in ES12, it is only supported in modern browsers. If that is a concern for you, then you can use String.prototype.replace()
instead with the global ("g
") flag (as it works in the same way and has great browser support).
Alternatively, you can also manually replicate digits for each color channel, for example, like so:
function normalizeHex(hex) { if (hex.length > 3) { return hex; } const red = `${hex[0]}${hex[0]}`; const green = `${hex[1]}${hex[1]}`; const blue = `${hex[2]}${hex[2]}`; return `${red}${green}${blue}`; } console.log(normalizeHex('fb0')); // ffbb00 console.log(normalizeHex('0fc')); // 00ffcc console.log(normalizeHex('fff')); // ffffff console.log(normalizeHex('000')); // 000000
You can also shorten this like so:
const normalizeHex = (hex) => ( (hex.length > 3) ? hex : `${hex[0]}${hex[0]}${hex[1]}${hex[1]}${hex[2]}${hex[2]}` );
In this version, the channel color code is manually repeated twice for each color channel to get a 6-digit hexadecimal color code. When the input value is larger than three, it is returned as is.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.