题解 | #颜色字符串转换#
颜色字符串转换
http://www.nowcoder.com/practice/80b08802a833419f9c4ccc6e042c1cca
function rgb2hex(sRGB) {
// 匹配是否符合颜色格式
let erx = /rgb\((\d{0,3},\s*){2}\d{0,3}\)/
if(!erx.test(sRGB)) {
return sRGB
}
// 找出xxx,xxx,xxx
let reg = /(\d{0,3},\s*){2}\d{0,3}/
let matchArr = sRGB.match(reg)[0].split(',')
let returnVal = '#'
for(let item of matchArr) {
item = item.trim()
if(item === '0') {
returnVal += '00'
} else {
returnVal += Number(item).toString(16)
}
}
return returnVal
}