HSL to Object

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28652{{"`HSL to Object`"}} javascript/data_types -.-> lab-28652{{"`HSL to Object`"}} javascript/arith_ops -.-> lab-28652{{"`HSL to Object`"}} javascript/comp_ops -.-> lab-28652{{"`HSL to Object`"}} javascript/higher_funcs -.-> lab-28652{{"`HSL to Object`"}} javascript/destr_assign -.-> lab-28652{{"`HSL to Object`"}} end

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 node to 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 with Number.
  • 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.

Other JavaScript Tutorials you may like