🔍

🎨 Color Hash Component

Below is a clean, drop-in JavaScript function that:

  1. Splits a paragraph into words.
  2. Uses a deterministic color hash (the clamped HSL version).
  3. Wraps each word in a <span> styled with its computed color.
  4. Returns safe HTML you can insert into the DOM.

🧩 Full Example


The morning mist still clung to the meadow as the first sunlight spilled over the eastern ridge, turning each blade of grass into a trembling filament of gold. Dewdrops shimmered like tiny lanterns along the edges of clover leaves, and a soft breeze carried the smell of damp earth and wild thyme. A pair of bluebirds darted from fence post to fence post, their wings flashing with quicksilver brightness, while somewhere deeper in the brush a chipmunk scurried, its tiny claws whispering over the fallen needles of a pine. Near the brook, dragonflies skimmed the surface, sketching invisible circles on the water that broke and reformed with every ripple. A cow lowed lazily from the far field, and beyond her, the old red barn breathed in sunlight through its wide doors. The world was quiet but full—every rustle, flutter, and glint seemed to hum with a slow, patient joy.
/**
 * Deterministic color for a string (HSL-based).
 */
function colorHashClamped(str, { saturation = 60, lightness = 55 } = {}) {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
    hash |= 0;
  }
  const hue = Math.abs(hash) % 360;
  return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
}

/**
 * Wrap each word of text in a span colored by its hash.
 * 
 * - Keeps punctuation intact.
 * - Preserves whitespace.
 */
function colorizeParagraph(text) {
  // Split by word boundaries while keeping delimiters
  return text.replace(/\b(\w+)\b/g, (match) => {
    const color = colorHashClamped(match);
    return `<span style="color:${color}">${match}</span>`;
  });
}

// 🧪 Example
const paragraph = "The quick brown fox jumps over the lazy dog.";
document.body.innerHTML = colorizeParagraph(paragraph);

✨ How it Works

  • /\b(\w+)\b/g matches “word” segments and leaves punctuation (., ,, etc.) untouched.
  • Each match is passed to colorHashClamped, which yields a stable HSL color.
  • The result replaces the word with a <span style="color:…">word</span>.

🖌️ Example Output (conceptually)

<span style="color:hsl(88,60%,55%)">The</span>
<span style="color:hsl(203,60%,55%)">quick</span>
<span style="color:hsl(145,60%,55%)">brown</span>
...

Each word will consistently get the same color anywhere it appears.

components published