Regular Expression & rgb2hex
regex
// 颜色字符串转换
function rgb2hex(sRGB = 'rgb(255, 255, 255)') {
const temp = sRGB;
// /^rgb([s*d+,]{2}[s*d+])$/
if(/^rgb([s*d+,]{2}[s*d+]{1})$/.test(temp)) {
// 符合 rgb 格式
} else {
// 输入不符合 rgb 格式,返回原始输入
return temp;
}
}
function rgb2hex (sRGB = 'rgb(255, 255, 255)') {
const regex = /^(rgb|RGB)((d{1,3}),s*(d{1,3}),s*(d{1,3}))/;
if(!regex.test(sRGB)){
return sRGB;
}else {
function hex(str) {
// string < number ❓⚠️
return str < 16 ? "0" + Number(str).toString(16) : Number(str).toString(16);
}
return sRGB.replace(regex, function(a, c, r, g, b){
console.log(`a, c`, a, c);
console.log(`r, g, b`, r, g, b);
console.log(`typeof r, typeof g, typeof b`, typeof r, typeof g, typeof b);
// console.log(`a, c, r, g, b`, a, c, r, g, b);
return "#" + hex(r) + hex(g) + hex(b);
})
}
}
function rgb2hex (sRGB = 'rgb(255, 255, 255)') {
const rgbStr = sRGB.toLowerCase();
// rgb 50%, RGB 50%
const regex = /^(rgb|RGB)((d{1,3}),s*(d{1,3}),s*(d{1,3}))/;
// const regex = /^rgb((d{1,3}),s*(d{1,3}),s*(d{1,3}))/;
if(!regex.test(rgbStr)){
return sRGB;
}else {
function hex(str) {
return str < 16 ? "0" + Number(str).toString(16) : Number(str).toString(16);
}
return rgbStr.toLowerCase().replace(regex, function(a, c, r, g, b){
console.log(`a, c`, a, c);
console.log(`r, g, b`, r, g, b);
// console.log(`a, c, r, g, b`, a, c, r, g, b);
return "#" + hex(r) + hex(g) + hex(b);
})
}
}
refs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Cheatsheet
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!