抄的,但是改进了
function rgb2hex(sRGB) {
// 找出每一组,然后替换16进制
let newSRGB = sRGB.replace(/\s+/g, "")
let regexp = /^rgb\(([01]\d{0,2}|2[0-5]{2}),([01]\d{0,2}|2[0-5]{2}),([01]\d{0,2}|2[0-5]{2})\)$/
if (!regexp.test(newSRGB)) return sRGB
return newSRGB.replace(regexp, (match, p1, p2, p3) => {
p1 = toHex(p1)
p2 = toHex(p2)
p3 = toHex(p3)
function toHex(p) {
return (+p).toString(16).length === 1 ? '0' + (+p).toString(16) : (+p).toString(16)
}
return `#${p1}${p2}${p3}`
})
}

京公网安备 11010502036488号