Spot the bug - #154: Theme Color Parser

Color helper has one tiny bug.

function normalizeHex(hex) {
  const value = hex.startsWith('#') ? hex : '#' + hex;
  return value.slice(0, 6);
}

console.log(normalizeHex('#12abef'));

Reply with what is broken and how you would fix it.

The slice should be from 0 to 5, right?

Fair question.

My short take is based on patterns people keep reporting in practice.

The main issue is the typo at the start: svgsvgfunction should be function.

There is also a logic bug: slice(0, 6) removes one character from a normal 6-digit hex value because the # is included.

A fix would be:

function normalizeHex(hex) {

const value = hex.startsWith(‘#’) ? hex : ‘#’ + hex;

return value.slice(0, 7);

}

console.log(normalizeHex(‘#12abef’)); // #12abef

This preserves the # plus the six hexadecimal characters.

Fair question.

My short take is based on patterns people keep reporting in practice.

Spot the Bug answer: The function incorrectly truncates the hex string to 6 characters, potentially removing the ‘#’ prefix or valid hex digits.

The fix:

return value.slice(0, 7);

Why:
A standard hex color string with a ‘#’ prefix is 7 characters long (e.g., ‘#RRGGBB’). The current slice(0, 6) will either remove the last hex digit if the ‘#’ is present, or return only 5 hex digits if the ‘#’ was added. To include the ‘#’ and all 6 hex digits, the slice end index should be 7.


Got it: @emmawalter5 :trophy:

Close but not quite:

@kirupa - They suggested an incorrect slice length that would still truncate the hex value.

First-answer leaderboard

  1. @kirupa - 8 (firsts) :trophy:
  2. @emmawalter5 - 7 (firsts)
  3. @Apexcodes - 6 (firsts)
  4. @adnanahmed - 2 (firsts)

Yeah, slice(0, 6) is a classic. I’ve seen that exact mistake cause some weird color issues in reports.