Skip to content
This repository was archived by the owner on Feb 20, 2019. It is now read-only.

Commit 9a881d0

Browse files
victoraugustKent C. Dodds
authored andcommitted
feat(hex2rgb): Add a function that converts colors in Hex to RGB format
Function accepts both #fff and #ffffff variants. Opacity can be omitted as well. #43
1 parent 6e4165d commit 9a881d0

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

src/hex2rgb.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
export default hex2rgb
2+
3+
/**
4+
* Original Source: http://stackoverflow.com/a/12342275
5+
*
6+
* This method will convert colors in Hex to RGB format.
7+
*
8+
* @param {String} hex - The Hex value to be converted
9+
* @param {Number} opacity - The opacity value of the color
10+
* @return {String} - The RGB value of the color
11+
*/
12+
function hex2rgb(hex, opacity) {
13+
let h = hex.replace('#', '')
14+
h = h.match(new RegExp(`(.{${h.length / 3}})`, 'g'))
15+
16+
for (let i = 0; i < h.length; i++) {
17+
h[i] = parseInt(h[i].length === 1 ? h[i] + h[i] : h[i], 16)
18+
}
19+
if (typeof opacity !== 'undefined') {
20+
h.push(opacity)
21+
}
22+
23+
return `rgba(${h.join(',')})`
24+
}

src/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import objectValuesToString from './object-values-to-string'
99
import getObjectSize from './get-object-size'
1010
import isArray from './is-array'
1111
import validateEmail from './validateEmail'
12+
import hex2rgb from './hex2rgb'
1213

1314
export {
1415
flatten,
@@ -22,4 +23,5 @@ export {
2223
getObjectSize,
2324
isArray,
2425
validateEmail,
26+
hex2rgb,
2527
}

test/hex2rgb.test.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import test from 'ava'
2+
import {hex2rgb} from '../src'
3+
4+
test('test hex without opacity value', t=>{
5+
const hex = '#ff0000'
6+
const expected = 'rgba(255,0,0)'
7+
const actual = hex2rgb(hex)
8+
t.deepEqual(actual, expected)
9+
})
10+
11+
test('test hex with opacity value', t=>{
12+
const hex = '#ff0000'
13+
const opacity = 1
14+
const expected = 'rgba(255,0,0,1)'
15+
const actual = hex2rgb(hex,opacity)
16+
t.deepEqual(actual,expected)
17+
})
18+
19+
test('test short hex without opacity value', t=>{
20+
const hex = '#f00'
21+
const expected = 'rgba(255,0,0)'
22+
const actual = hex2rgb(hex)
23+
t.deepEqual(actual, expected)
24+
})

0 commit comments

Comments
 (0)