Extend hex value

OSCC · JavaScript, String · Sep 15, 2020

Extends a 3-digit color code to a 6-digit color code.

const extendHex = shortHex =>
  '#' +
  shortHex
    .slice(shortHex.startsWith('#') ? 1 : 0)
    .split('')
    .map(x => x + x)
    .join('');
extendHex('#03f'); // '#0033ff'
extendHex('05a'); // '#0055aa'

Recommended snippets & collections

  • Working with color in JavaScript requires some understanding of color formats and conversions. Luckily, this snippet collection's got you covered.

  • Hex to RGB

    JavaScript, String

    Converts a color code to an rgb() or rgba() string if alpha value is provided.

  • RGB to hex

    JavaScript, String

    Converts the values of RGB components to a hexadecimal color code.

  • HSL to object

    JavaScript, String

    Converts an hsl() color string to an object with the values of each color.