Created
August 30, 2017 16:11
-
-
Save pgaskin/868dac9bd028f219ebd053e36a2d7737 to your computer and use it in GitHub Desktop.
Parses a legacy html color
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// processColor processes a legacy html color | |
// The legacy html colors apply only to colors in the bgcolor attribute | |
// | |
// Copyright 2017 Patrick G | |
// Based on http://scrappy-do.blogspot.ca/2004/08/little-rant-about-microsoft-internet.html | |
// Also see https://stackoverflow.com/questions/8318911/why-does-html-think-chucknorris-is-a-color | |
function processColor(color) { | |
// Remove the hash | |
color = color.replace("#", ""); | |
// Convert to lowercase | |
color = color.toLowerCase() | |
// Replace all non-hex chars with a zero | |
color = color.replace(/[^A-Fa-f0-9]/g, "0") | |
if (color.length < 3) { | |
// Append zeros until length is 3 | |
while (color.length != 3) { | |
color = color + "0"; | |
} | |
} else if (color.length == 3) { | |
// Prepend a zero before each character | |
color = "0" + color.split("")[0] + "0" + color.split("")[1] + "0" + color.split("")[2] | |
} else if (color.length > 3) { | |
// Append zeros until length is divisible by 3 | |
while (color.length % 3 != 0) { | |
color = color + "0"; | |
} | |
} | |
// Split into 3 even chunks (for red, green, blue) | |
var rgbHex = []; | |
var chunkSize = color.length / 3; | |
for (var i = 0; i < color.length; i += chunkSize) { | |
rgbHex.push(color.substring(i, i + chunkSize)); | |
} | |
// For each chunk | |
for (var i = 0; i < rgbHex.length; i++) { | |
// Until length is 2 | |
while (rgbHex[i].length != 2) { | |
if (rgbHex[i].length > 8) { | |
// If length is greater than 8, remove first char | |
rgbHex[i] = rgbHex[i].substring(1); | |
} else { | |
// If length is less than 8, remove last char | |
rgbHex[i] = rgbHex[i].substring(0, rgbHex[i].length - 1); | |
} | |
} | |
} | |
// Add the hash symbol again to make the color | |
color = "#" + rgbHex.join(""); | |
return color; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment