题目描述:
将 rgb 颜色字符串转换为十六进制的形式,如 rgb(255, 255, 255) 转为 #ffffff
示例1:
输入
‘rgb(255, 255, 255)’
输出
#ffffff
function rgb2hex(sRGB) {
var reg = /^\d+$/
var saveSrgb = sRGB
var sRGB = sRGB.slice(4,-1)
resArr = sRGB.split(',')
var res = '#'
if (resArr.length!=3) {
return saveSrgb
}
for(var i=0;i<resArr.length;i++){
if (!reg.test(resArr[i].trim())) {
return saveSrgb
}
var num = parseInt(resArr[i].trim())
if (num>=0 && num<=255 && !isNaN(num)) {
var temp = num.toString(16)
if (temp.length == 1) {
temp = '0'+temp
}
res+=temp
}else{
return saveSrgb
}
}
return res
}
注意点:
<html>
<head>
<meta charset="utf-8">
<title>进制转换title>
head>
<body>
<script type="text/javascript">
// 十进制转16进制
var array = [170,30,19,0,0,0,0,0,0,3,164,0,0,1,0,13,14,15,0,255,127,255,200,255,0,55,127,1,255,88,171];
var newArray = array.map(item=>{
return item.toString(16);
});
console.log(newArray);
// 十六进制转十进制
var arr = ['aa','0f','13','00','00','00','00','00','00','02','01','01','00','00','00','da'];
var arr2 = arr.map(item=>{
return parseInt(item,16);
})
console.log(arr2);
script>
body>
html>