Get each color component from RGB string in Javascript

Did you ever think about separating each color component (red, green, blue) from an RGB color string? Here in this article, I am going to show you how you can separate and get the color component from an RGB color string in Javascript.

I hope you are familiar with RGB color.

An RGB color consists of red, green and blue. It specifies with rgb(red, green, blue) where each parameter defines the intensity of that color as the integer that can be between 0 to 255.

We can easily get each color parameter item’s integer value using javaScript. It can be done within a few lines of code.

JavaScript code to get color component from RGB string

Below is the JavaScript code that will do our task:

var rgbColor = 'rgb(46, 123, 14)';
rgbArr = rgbColor.substring(4, rgbColor.length-1).replace(/ /g, '').split(',');
console.log(rgbArr);

Now if you run the above code, you will get an array that will consist of the RGB color components. Below is the result we see in the console if we run the code:

["46", "123", "14"]

In our code, we take the RGB component part only using the substring() method. We split RGB color components by “comma” using the split() method. Thus, we able to get an array of RGB color items.

Now it is very easy to take each item from our array which will contain a color item of RGB color. Below is how we can get red, green and blue component from an RGB color and display it on the console:

console.log(rgbArr[0]); // Red component
console.log(rgbArr[1]); // Green component
console.log(rgbArr[2]); //Blue component

Also, read:

So this is the way to get each color item from an RGB color in JavaScript.

 

Leave a Reply

Your email address will not be published.