🎨 Color Hash Component
Below is a clean, drop-in JavaScript function that:
- Splits a paragraph into words.
- Uses a deterministic color hash (the clamped HSL version).
- Wraps each word in a
<span>styled with its computed color. - Returns safe HTML you can insert into the DOM.
🧩 Full Example
/**
* 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/gmatches “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.