how to convert rgb to hex and hex to rgb in javascript

How to Convert RGB to Hex and Hex to RGB in JavaScript

RGB (Red-Green-Blue) and Hex are two popular formats of storing color values. Often you may need to convert RGB to Hex and Hex to RGB. Although there are many online tools available for this purpose, if you want to convert a large number of values, or you want to automate conversion then you may not be able to do it with online tools. In this article, we will learn how to convert RGB to Hex and Hex to RGB in JavaScript.


How to Convert RGB to Hex and Hex to RGB in JavaScript

Here is a JavaScript function to convert RGB to Hex.

function componentToHex(c) {
  var hex = c.toString(16);
  return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
  return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

alert(rgbToHex(255, 255, 255)); // #ffffff

In the above code, we first define a helper function that will take a component of RGB color code (either red, blue or green) and return its hex equivalent. We also define the main rgbtoHex() function which calls the above helper function for each component of RGB color code, concatenates the hex strings for each component, prepends the hash # sign required for hex codes, and returns the complete hex code.

We also define a JavaScript function to convert hex to rgb.

function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

alert(hexToRgb("#ffffff").g); // "{r:255,g:255,b:255}";

In the above code, we first split the 6 character hex code to an array of 3 items and store them in result array. Then we convert each hex to integer value using parseInt. The int values are the RGB component colors.

In this article, we have leant how to convert RGB to Hex and vice versa.

Also read:

How to Store Emoji in MySQL Database
How to Select Nth Row in Database Table
How to Search String in Multiple Tables in Database
How to Split Field into Two in MySQL
How to Fix Can’t Connect to Local MySQL

Leave a Reply

Your email address will not be published. Required fields are marked *