# 实现rgb(255, 255, 255)到#FFFFFF
分为以下三个步骤:
- 从 rgb(255, 255, 255) 中提取出 r=255 、 g=255 、 b=255
- 将 r 、 g 、 b 转换为十六进制,不足两位则补零
- 组合 #
1. 从 rgb(255, 255, 255) 中提取出 r=255 、 g=255 、 b=255
方式一:利用 match
function rgb2hex(sRGB) {
const reg = /^(rgb|RGB)\(\s*(\d{1,3})\s*,\s*(\d{1,3}\s*),\s*(\d{1,3})\s*\)$/
const rbg = sRGB.match(reg)
return rbg
}
// 测试
console.log(rgb2hex('rgb(255, 255, 255)'))
// [
// 'rgb(255, 255, 255)',
// 'rgb',
// '255',
// '255',
// '255',
// index: 0,
// input: 'rgb(255, 255, 255)',
// groups: undefined
// ]
方式二:利用 match 方法2
function rgb2hex(sRGB) {
const rgb = sRGB.match(/\d+/g);
return rgb
}
// 测试
console.log(rgb2hex('rgb(255, 255, 255)'))
// [ '255', '255', '255' ]
// [ '255', '255', '255' ]
方法三:利用replace+split
function rgb2hex(sRGB) {
const rgb = sRGB.replace(/(?:\(|\)|rgb|RGB)*/g, '').split(',')
return rgb
}
// 测试
console.log(rgb2hex('rgb(255, 255, 255)'))
// [ '255', ' 255', ' 255' ]
2. 将 r 、 g 、 b 转换为十六进制,不足两位则补零
转换为十六进制,可采用:
(+n).toString(16)
Number(n).toString(16)
不足两位则补零:
('0' + num).slice(-2)
num.padStart(2, '0')
(r < 16? '0':'') + num
num.length < 2 ? '0' + num : num
((1 << 24) + (Number(r) << 16) + (Number(g) << 8) + Number(b)).toString(16).slice(1)
3. 组合 #
rgb.reduce((acc, cur) => acc + hex, '#').toUpperCase()
将以上的三个步骤进行组合即可。示例:
function rgb2hex(sRGB) {
let rgb = sRGB.match(/\d+/g)
rgb = rgb.map(item => {
item = (+item).toString(16)
item= (+item < 16 ? '0' : '') + item
return item
})
return rgb.reduce((acc, cur) => acc + cur, '#').toUpperCase()
}
console.log(rgb2hex('rgb(25, 55, 255)'))