Parse and stringify CSS color values — hex, rgb, hsl, and named colors
npm install @philiprehberger/color-stringParse and stringify CSS color values -- hex, rgb, hsl, and named colors.
npm install @philiprehberger/color-string
import { parse, toHex, toRgb, toHsl, isValid } from '@philiprehberger/color-string';
const color = parse('#ff0000');
// => { r: 255, g: 0, b: 0, a: 1 }
parse('rgb(255, 0, 0)');
// => { r: 255, g: 0, b: 0, a: 1 }
parse('hsl(0, 100%, 50%)');
// => { r: 255, g: 0, b: 0, a: 1 }
parse('red');
// => { r: 255, g: 0, b: 0, a: 1 }
toHex({ r: 255, g: 0, b: 0, a: 1 });
// => "#ff0000"
toRgb({ r: 255, g: 0, b: 0, a: 1 });
// => "rgb(255, 0, 0)"
toHsl({ r: 255, g: 0, b: 0, a: 1 });
// => "hsl(0, 100%, 50%)"
isValid('red');
// => true
isValid('notacolor');
// => false
parse(str: string): Color | nullParse a CSS color string into a Color object. Supports hex (#RGB, #RGBA, #RRGGBB, #RRGGBBAA), rgb()/rgba(), hsl()/hsla(), and named colors.
toHex(color: Color): stringConvert a Color to a hex string. Includes alpha channel if a < 1.
toRgb(color: Color): stringConvert a Color to an rgb() or rgba() string.
toHsl(color: Color): stringConvert a Color to an hsl() or hsla() string.
isValid(str: string): booleanReturns true if the string can be parsed as a valid CSS color.
Colorinterface Color {
r: number; // 0-255
g: number; // 0-255
b: number; // 0-255
a: number; // 0-1
}
npm install
npm run build
npm test
If you find this project useful: