Alines Webマガジン

codewars converting hex to rgb value solving using javascript CC57YULF7nA

📅 October 29, 2026📖 Verified Publication
```html Codewars: Converting Hex to RGB Using JavaScript — Complete Playbook (CC57YULF7nA)

Codewars: Converting Hex to RGB Using JavaScript — Complete Playbook (CC57YULF7nA)

The Hex to RGB Converter kata is one of the most frequently attempted beginner problems on Codewars. It tests your grasp of string manipulation, base conversion, and regex fundamentals in JavaScript. This playbook gives you everything you need to solve it cleanly and understand the underlying concepts deeply.

Key Takeaways

  • A hex color string like "#F9B403" maps to RGB values by splitting it into three pairs: red "F9", green "B4", blue "03"
  • Each two-character hex pair represents values from 0–255, exactly matching the RGB range
  • parseInt(pair, 16) is the standard way to convert a hex string to a decimal number in JavaScript
  • Regex-based solutions are concise; string slice() or substring() approaches are more readable for beginners
  • The final output should be formatted as rgb(R, G, B) with integer values
  • Codewars may include the # prefix or omit it — always normalize input first

Understanding the Problem

What Is a Hex Color Code?

Hex color codes are six-digit hexadecimal numbers prefixed with a hash symbol (#). They represent red, green, and blue channels as two-digit pairs:

  • Characters 1–2: Red channel
  • Characters 3–4: Green channel
  • Characters 5–6: Blue channel

For example, #1A2B3C breaks down into red 1A, green 2B, and blue 3C.

What Does the Codewars Kata Expect?

The kata provides a hex string and expects an RGB string in this exact format:

  • Input: "#F9B403"
  • Output: "rgb(249, 180, 3)"

Before writing any code, confirm whether the test cases include the # prefix. The safest approach strips it if present.

Step-by-Step Solutions

Method 1: Using slice() and parseInt()

This is the most readable approach and ideal for learning.

function hexToRgb(hex) {
  // Remove the # prefix if it exists
  const cleanHex = hex.replace(/^#/, '');

  // Split into three 2-character pairs
  const r = parseInt(cleanHex.slice(0, 2), 16);
  const g = parseInt(cleanHex.slice(2, 4), 16);
  const b = parseInt(cleanHex.slice(4, 6), 16);

  return `rgb(${r}, ${g}, ${b})`;
}

console.log(hexToRgb("#F9B403"));
// Output: "rgb(249, 180, 3)"

Method 2: Using Regex with Capturing Groups

Regex produces a compact one-liner that experienced developers favor.

function hexToRgb(hex) {
  const result = hex.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);

  if (!result) {
    throw new Error("Invalid hex color");
  }

  const r = parseInt(result[1], 16);
  const g = parseInt(result[2], 16);
  const b = parseInt(result[3], 16);

  return `rgb(${r}, ${g}, ${b})`;
}

console.log(hexToRgb("#1A2B3C"));
// Output: "rgb(26, 43, 60)"

Method 3: Using a Loop with match()

This approach generalizes well and demonstrates how to avoid repetition.

function hexToRgb(hex) {
  const pairs = hex.replace(/^#/, '').match(/.{2}/g);
  const rgbValues = pairs.map(pair => parseInt(pair, 16));

  return `rgb(${rgbValues.join(', ')})`;
}

console.log(hexToRgb("#FF00AA"));
// Output: "rgb(255, 0, 170)"

Method Comparison Table

Method Readability Conciseness Handles Invalid Input Best For
slice() + parseInt() High Medium No Beginners, learning
Regex capturing groups Medium High Yes (with validation) Production code, interviews
Loop with match() Medium Medium No Scaling to other bases

Checklist: Passing the Codewars Kata

  • Strip the # prefix — test cases may or may not include it
  • Validate hex length — ensure exactly 6 characters after stripping
  • Use base 16 explicitly — always pass 16 as the second argument to parseInt()
  • Handle lowercase and uppercase — parseInt() accepts both automatically
  • Format the output string precisely — match the exact spacing: rgb(R, G, B)
  • Consider edge cases — test with "#000000", "#FFFFFF", and "#000001"
  • Add error handling — throw or return a fallback for malformed input
  • Run all test cases before submitting — Codewars uses hidden tests too

Common Pitfalls to Avoid

  • Calling parseInt() without base 16 — defaults to base 10 and produces wrong results for letters like A–F
  • Hard-coding array indices — if you use hex.substring(1, 3), remember the # position
  • Returning objects instead of formatted strings — the kata expects rgb(...) format, not {r, g, b}
  • Ignoring case sensitivity — while parseInt() handles it, custom validation logic may not
  • Missing leading-zero pairs — "#03" in the blue channel must become 3, not NaN

Advanced: Handling Edge Cases Gracefully

For production-quality code or harder variations of this kata, wrap your solution with proper validation.

function hexToRgb(hex) {
  const hexPattern = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
  const match = hex.match(hexPattern);

  if (!match) {