题解 | #颜色字符串转换#
颜色字符串转换
https://www.nowcoder.com/practice/80b08802a833419f9c4ccc6e042c1cca
抄的,但是改进了
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}`
})
}
查看1道真题和解析