RGB to Object

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore a JavaScript function that converts an rgb() color string to an object with the values of each color. This function uses a combination of string manipulation and array destructuring to parse the numeric values from the input string and store them in a new object. This lab will help you understand how to work with strings, arrays, and objects 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-28658{{"`RGB to Object`"}} javascript/data_types -.-> lab-28658{{"`RGB to Object`"}} javascript/arith_ops -.-> lab-28658{{"`RGB to Object`"}} javascript/comp_ops -.-> lab-28658{{"`RGB to Object`"}} javascript/higher_funcs -.-> lab-28658{{"`RGB to Object`"}} javascript/destr_assign -.-> lab-28658{{"`RGB to Object`"}} end

Converting RGB to Object

To convert an rgb() color string to an object with the values of each color, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use String.prototype.match() to get an array of 3 strings with the numeric values.
  3. Use Array.prototype.map() in combination with Number to convert them into an array of numeric values.
  4. Use array destructuring to store the values into named variables and create an appropriate object from them.

Here's the code you can use:

const toRGBObject = (rgbStr) => {
  const [red, green, blue] = rgbStr.match(/\d+/g).map(Number);
  return { red, green, blue };
};

toRGBObject("rgb(255, 12, 0)"); // {red: 255, green: 12, blue: 0}

Summary

Congratulations! You have completed the RGB to Object lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like