toString() Function in JS | Convert RGB Code into HEX Code

Date Published: 10/09/2020 Published By: JaiSchool

We can convert RGB color code into HEX code. Simply first, we need to convert the RGB code into a number (data type) by using the Number() function. Then apply the toString() function on it. The function toString(16) needs 16 as its parameter.

Example:~

<!DOCTYPE html>
<html>
<head>
  <title>RGB to HEX</title>
</head>
<body>

<script>
		var red=Number(255).toString(16);
		var green=Number(0).toString(16);
		var blue=Number(0).toString(16);
		if(red.length == 1){red = "0"+red;}
		if(green.length == 1){green = "0"+green;}
		if(blue.length == 1){blue = "0"+blue;}
		var hex_code="#"+red+green+blue;
		alert(hex_code);
	</script>
</body>
</html>

Publish A Comment

Leave a Reply

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