1. rgb 中每个 , 后面的空格数量不固定
2. 十六进制表达式使用六位小写字母
3. 如果输入不符合 rgb 格式,返回原始输入
样例:
输入:'rgb(255, 255, 255) '
输入:'rgb(255, 255, 255) '
输出:'#ffffff'
'rgb(255, 255, 255)'
#ffffff
function rgb2hex(sRGB) {
// 判断是否合法
const regex = /^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/i;
const isValid = regex.test(sRGB);
if (!isValid) {
return sRGB;
}
// 提取数字
const _regex = /\d+/g;
const result = sRGB.match(_regex);
const newResult = result.map((item) => {
// 转化为16进制并补全
const i = Number(item).toString(16);
return i.length === 1 ? `0${i}` : i;
});
// 返回连接后的字符串
return `#${newResult.join("")}`;
} function rgb2hex(sRGB) {
if(/rgb\((\d+)\, *(\d+)\, *(\d+)\)/.test(sRGB)){
let arr = [RegExp.$1,RegExp.$2,RegExp.$3],str = '#'
for (let i = 0; i < arr.length; i++) {
if(arr[i]>255) return sRGB
str += arr[i] === '0' ? '00' : Number.parseInt(arr[i]).toString(16)
}
return str
}
return sRGB
} function rgb2hex(sRGB) {
let reg=/rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)/
let result = reg.exec(sRGB)
let to16 = (num)=>{
let num16 = (num*1).toString(16)
return num16.length==1?"0"+num16:num16
}
return result?`#${to16(RegExp.$1)}${to16(RegExp.$2)}${to16(RegExp.$3)}`:sRGB
} function rgb2hex(sRGB) {
const reg = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/
if (!reg.test(sRGB)) {
return sRGB
}
// String.prototype.match
return hexUseMatch(sRGB, reg)
// RegExp.prototype.exec
// return hexUseExec(sRGB, reg)
// String.prototype.replace
// return hexUseReplace(sRGB, reg)
// RegExp $
// return hexUseRegExp$()
}
function hexUseMatch(sRGB, reg) {
const nums = sRGB.match(reg).slice(1)
if (!nums.every(checkValidNumber)) {
return sRGB
}
return combineHex(nums)
}
function hexUseExec(sRGB, reg) {
const nums = reg.exec(sRGB).slice(1)
if (!nums.every(checkValidNumber)) {
return sRGB
}
return combineHex(nums)
}
function hexUseReplace(sRGB, reg) {
return sRGB.replace(reg, ($1, $2, $3, $4) => {
var nums = [$2, $3, $4]
if (!nums.every(checkValidNumber)) {
return sRGB
}
return combineHex(nums)
})
}
function hexUseRegExp$() {
var nums = [RegExp.$1, RegExp.$2, RegExp.$3]
if (!nums.every(checkValidNumber)) {
return sRGB
}
return combineHex(nums)
}
function combineHex(nums) {
return nums.reduce((acc, num) => {
return acc + num2Hex(num)
}, '#')
}
function checkValidNumber(num) {
// not float number
if (/\./.test(num)) {
return false
}
// 0-255
return num >= 0 && num <= 255
}
function num2Hex(num) {
if (typeof num !== 'number') {
num = Number(num)
}
const hex = num.toString(16)
return hex.length < 2 ? `0${hex}` : hex
}