function toFixed(a, fix = 4) {
const str = `${a}`
if (/^(\d+)(\.\d+)?/i.test(str)) {
const left = RegExp.$1
const right = RegExp.$2.slice(1, Math.min(fix, RegExp.$2.length - 1) + 1)
const final = [left, right].filter(Boolean).join('.')
return Number(final)
}
return ''
}
function getHex(a) {
let cur = toFixed(a)
let hex = 0x00
while(hex <= 0xff) {
let tmp = toFixed(hex / 255)
if (tmp == cur) {
break
}
hex += 1
}
return hex.toString(16)
}
function getRgb(str) {
let red = 0
let green = 0
let blue = 0
if (/red\="(\d+(?:\.\d+)?)"/i.test(str)) {
red = getHex(RegExp.$1)
}
if (/green\="(\d+(?:\.\d+)?)"/i.test(str)) {
green = getHex(RegExp.$1)
}
if (/blue\="(\d+(?:\.\d+)?)"/i.test(str)) {
blue = getHex(RegExp.$1)
}
return `#${red}${green}${blue}`
}
console.log(getRgb('red="0.20000000000000001" green="0.20000000000000001" blue="0.20000000000000001"'))
console