颜色字符串转换
AprilTong 11/29/2021 简单算法
# 颜色字符串转换
- 描述
将 rgb 颜色字符串转换为十六进制的形式,如 rgb(255, 255, 255) 转为 #ffffff
- rgb 中每个 , 后面的空格数量不固定
- 十六进制表达式使用六位小写字母
- 如果输入不符合 rgb 格式,返回原始输入
- 示例
输入:'rgb(255, 255, 255)'
输出:#ffffff
1
2
3
2
3
# 自己实现
function rgb2hex(sRGB) {
if (/^(rgb|RGB)/.test(sRGB)) {
let arr = sRGB.replace(/\(|\)|rgb|RGB/g, '').split(',')
let strHex = '#'
arr.forEach((item) => {
let result = Number(item).toString(16)
if (result.length < 2) {
result = '0' + result
}
strHex += result
})
if (strHex.length !== 7) {
strHex = sRGB
}
return strHex
} else {
return sRGB
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 讨论中别人比较好的实现
方法一:
function rgb2hex(sRGB) {
if (/^(rgb|RGB)/.test(sRGB)) {
let result = sRGB
.replace(/\(|\)|rgb|RGB/g, '')
.split(',')
.map((item) =>
Number(item)
.toString(16)
.padStart(2, '0')
)
.join('')
return `#${result}`
} else {
return sRGB
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
方法二:
function rgb2hex(sRGB) {
let hex = (n) => (n < 16 ? '0' + (+n).toString(16) : (+n).toString(16))
return sRGB.replace(/^rgb\((\d+)\s*\,\s*(\d+)\s*\,\s*(\d+)\)$/g, function(a, r, g, b) {
return `#${hex(r)}${hex(g)}${hex(b)}`
})
}
1
2
3
4
5
6
2
3
4
5
6