Introduction
In this lab, we will explore how to convert an rgb() color string to an array of numeric values using JavaScript. The lab will guide you through the steps required to extract the color values from the string and convert them into an array. This skill is useful for web development, especially when working with graphics and design.
Converting RGB String to an Array
To convert an rgb() color string to an array of values, 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. - Use
Array.prototype.map()in combination withNumberto convert them into an array of numeric values.
Here's the code that you can use:
const toRGBArray = (rgbStr) => rgbStr.match(/\d+/g).map(Number);
To test the function, call it with an rgb() color string as the argument, like this:
toRGBArray("rgb(255, 12, 0)"); // [255, 12, 0]
Summary
Congratulations! You have completed the RGB to Array lab. You can practice more labs in LabEx to improve your skills.