Changes the lightness value of an hsl()
color string.
String.prototype.match()
to get an array of 3 strings with the numeric values.Array.prototype.map()
in combination with Number
to convert them into an array of numeric values.0
and 100
), using Math.max()
and Math.min()
.hsl()
string with the updated value.const changeLightness = (delta, hslStr) => {
const [hue, saturation, lightness] = hslStr.match(/\d+/g).map(Number);
const newLightness = Math.max(
0,
Math.min(100, lightness + parseFloat(delta))
);
return `hsl(${hue}, ${saturation}%, ${newLightness}%)`;
};
changeLightness(10, 'hsl(330, 50%, 50%)'); // 'hsl(330, 50%, 60%)'
changeLightness(-10, 'hsl(330, 50%, 50%)'); // 'hsl(330, 50%, 40%)'
Snippet collection
Working with color in JavaScript requires some understanding of color formats and conversions. Luckily, this snippet collection's got you covered.
JavaScript, String
Converts an hsl()
color string to an object with the values of each color.
JavaScript, String
Converts an hsl()
color string to an array of values.
JavaScript, String
Converts an rgb()
color string to an object with the values of each color.