Skip to content

Instantly share code, notes, and snippets.

@carlos3g
Created June 13, 2024 15:23
Show Gist options
  • Save carlos3g/ba42b8e1353db98c43b6f77a01a11e44 to your computer and use it in GitHub Desktop.
Save carlos3g/ba42b8e1353db98c43b6f77a01a11e44 to your computer and use it in GitHub Desktop.
text to color | base 36 to 16
// see: https://www.charlie-coleman.com/experiments/1
export const textToColor = (unsafeColor: string): string => {
// Remove all non-alphanumeric characters and spaces
let color = unsafeColor.replace(/\s+/g, '').replace(/[^a-zA-Z0-9]+/g, '');
// Calculate required length and padding
const lengthC = color.length;
const amount = Math.ceil(lengthC / 3);
const add = amount * 3 - lengthC;
// Pad the string if necessary
if (add > 0) {
color = color.padEnd(lengthC + add, color);
}
// Split the string into three parts
const red36 = color.substring(0, amount) || '0';
const green36 = color.substring(amount, amount * 2) || '0';
const blue36 = color.substring(amount * 2, amount * 3) || '0';
// Convert from base-36 to base-10
const red = parseInt(red36, 36);
const green = parseInt(green36, 36);
const blue = parseInt(blue36, 36);
// Convert to base-16 and pad to ensure two digits
const red16 = red.toString(16).padStart(2, '0');
const green16 = green.toString(16).padStart(2, '0');
const blue16 = blue.toString(16).padStart(2, '0');
// Construct and return the final color string
return `#${red16}${green16}${blue16}`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment