Introduction
In this lab, we will be exploring how to convert an hsl() color string to an object with individual values for hue, saturation, and lightness. We will be utilizing string manipulation and array methods to extract the numeric values and store them into a new object with named properties. By the end of this lab, you will have a better understanding of how to work with color values in JavaScript.
HSL to Object Conversion
To convert an hsl() color string into an object with the numeric values of each color, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
String.prototype.match()to get an array of 3 strings with the numeric values. - Convert the strings into an array of numeric values using
Array.prototype.map()in combination withNumber. - Store the values into named variables using array destructuring.
- Create an appropriate object from the named variables.
const toHSLObject = (hslStr) => {
const [hue, saturation, lightness] = hslStr.match(/\d+/g).map(Number);
return { hue, saturation, lightness };
};
Example usage:
toHSLObject("hsl(50, 10%, 10%)"); // { hue: 50, saturation: 10, lightness: 10 }
Summary
Congratulations! You have completed the HSL to Object lab. You can practice more labs in LabEx to improve your skills.