Any Hex Form Modular Approach
The main challenge is that as of 2018 there are a few forms of HEX. The 6 char traditional form, the 3 char shorten form, and a new 4 and 8 char form that includes alpha. The following function can handle any HEX form.
const isValidHex = (hex) => /^#([A-Fa-f0-9]{3,4}){1,2}$/.test(hex)
const getChunksFromString = (st, chunkSize) => st.match(new RegExp(`.{${chunkSize}}`, "g"))
const convertHexUnitTo256 = (hexStr) => parseInt(hexStr.repeat(2 / hexStr.length), 16)
const getAlphafloat = (a, alpha) => {
if (typeof a !== "undefined") {return a / 255}
if ((typeof alpha != "number") || alpha <0 || alpha >1){
return 1
}
return alpha
}
export const hexToRGBA = (hex, alpha) => {
if (!isValidHex(hex)) {throw new Error("Invalid HEX")}
const chunkSize = Math.floor((hex.length - 1) / 3)
const hexArr = getChunksFromString(hex.slice(1), chunkSize)
const [r, g, b, a] = hexArr.map(convertHexUnitTo256)
return `rgba(${r}, ${g}, ${b}, ${getAlphafloat(a, alpha)})`
}
Alpha could be provided to the function in the following ways:
- As part of a 4, or 8 form HEX .
- As a second parameter between 0-1,
OutPut
const c1 = "#f80"
const c2 = "#f808"
const c3 = "#0088ff"
const c4 = "#0088ff88"
const c5 = "#98736"
console.log(hexToRGBA(c1)) // rgba(255, 136, 0, 1)
console.log(hexToRGBA(c2)) // rgba(255, 136, 0, 0.53125)
console.log(hexToRGBA(c3)) // rgba(0, 136, 255, 1)
console.log(hexToRGBA(c4)) // rgba(0, 136, 255, 0.53125)
console.log(hexToRGBA(c5)) // Uncaught Error: Invalid HEX
console.log(hexToRGBA(c1, 0.5)) // rgba(255, 136, 0, 0.5)
console.log(hexToRGBA(c3, 0.5)) // rgba(0, 136, 255, 0.5)