Table of Contents
Use ParseInt and String.substring methods
Example
Use Array.map() and String.match() methods
Home Web Front-end JS Tutorial How to convert Hex value to RGBA value using JavaScript?

How to convert Hex value to RGBA value using JavaScript?

Aug 31, 2023 pm 02:01 PM

如何使用 JavaScript 将 Hex 值转换为 RGBA 值?

When designing web pages, we use colors to make the web pages more attractive and attractive. We usually use hexadecimal codes to represent colors, but sometimes we need to add transparency to a color, which can be achieved through RGBA values.

Hexadecimal color values ​​are represented by #RRGGBBAA, RGBA color values ​​are represented by rgba(red, green, blue, alpha). Here are some examples of RGBA and hexadecimal values ​​-

Input:     #7F11E0
Output:  rgba( 127, 17, 224, 1 )
Input:     #1C14B0
Output: rgba( 28, 20, 176, 1 )
Copy after login

In this article, we will discuss various ways to convert Hex to RGBA using Javascript.

  • Use parseInt and String.substring methods

  • Using array destructuring and regular expressions

Use ParseInt and String.substring methods

The parseInt() function accepts two parameters: a string representing a number and a number representing the base. It then converts the string to an integer in the specified base and returns the result.

String.substring method is used to extract some parts of a string by getting the start and end positions.

To convert HEX to RGBA we use the following steps.

  • Leave # and use the String.substring method to extract a pair of two characters of the hexadecimal string one by one.

  • After extraction, use the parseInt method to convert each pair to an integer. We know that these pairs are hex codes, so we need to pass 16 to the second argument of parseInt.

  • After converting each pair of hexadecimal codes to integers, concatenate them into RGBA format.

Example

In this example, we convert the hex code to RGBA.

<!DOCTYPE html>
<html>
<head>
   <title>Convert Hex to RGBA value using JavaScript</title>
</head>
<body>
   <h3>Converting Hex to RGBA value parseInt() and String.substring() methods</h3>
   <p id="input"> Hex Value: </p>
   <p id="output"> RGBA Value: </p>
   <script>
      let hex = "#7F11E0";
      let opacity = "1";
      // Convert each hex character pair into an integer
      let red = parseInt(hex.substring(1, 3), 16);
      let green = parseInt(hex.substring(3, 5), 16);
      let blue = parseInt(hex.substring(5, 7), 16);
      
      // Concatenate these codes into proper RGBA format
      let rgba  = ` rgba(${red}, ${green}, ${blue}, ${opacity})`
      
      // Get input and output fields
      let inp = document.getElementById("input");
      let opt = document.getElementById("output");
      
      // Print the values
      inp.innerHTML += hex;
      opt.innerText += rgba;
   </script>
</body>
</html>
Copy after login

Use Array.map() and String.match() methods

Javascript Array The map() method creates a new array containing the results of calling the provided function on each element in the array.

String.match method is used to retrieve matches when matching a string with a regular expression.

To convert HEX to RGBA we use the following steps.

  • Use the /\w\w/g regular expression and the String.match method to match every sequence of two consecutive alphanumeric characters of a hexadecimal string.

  • You will get three pairs of alphanumeric characters in an array and convert these characters to integers using Array.map and parseInt methods.

Example

In this example, we convert the hex code to RGBA.

<!DOCTYPE html>
<html>
<head>
   <title>Converting Hex to RGBA value using JavaScript</title>
</head>
<body>
   <h3>Convert Hex to RGBA value using Array.map() and String.match() methods</h3>
   <p id="input"> Hex: </p>
   <p id="output"> RGBA: </p>
   <script>
      let hex = "#7F11E0";
      let opacity = "1";
      
      // Use a regular expression to extract the individual color values from the hex string
      let values = hex.match(/\w\w/g);
      
      // Convert the hex color values to decimal values using parseInt() and store them in r, g, and b
      let [r, g, b] = values.map((k) => parseInt(k, 16)) 
      
      // Create the rgba string using the decimal values and opacity
      let rgba = ` rgba( ${r}, ${g}, ${b}, ${opacity} )`
      
      // Get input and output fields
      let inp = document.getElementById("input");
      let opt = document.getElementById("output");
      
      // Print the values
      inp.innerHTML += hex;
      opt.innerText += rgba;      
   </script>
</body>
</html>
Copy after login

The above is the detailed content of How to convert Hex value to RGBA value using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Replace String Characters in JavaScript

jQuery Check if Date is Valid jQuery Check if Date is Valid Mar 01, 2025 am 08:51 AM

jQuery Check if Date is Valid

jQuery get element padding/margin jQuery get element padding/margin Mar 01, 2025 am 08:53 AM

jQuery get element padding/margin

10 jQuery Accordions Tabs 10 jQuery Accordions Tabs Mar 01, 2025 am 01:34 AM

10 jQuery Accordions Tabs

10 Worth Checking Out jQuery Plugins 10 Worth Checking Out jQuery Plugins Mar 01, 2025 am 01:29 AM

10 Worth Checking Out jQuery Plugins

HTTP Debugging with Node and http-console HTTP Debugging with Node and http-console Mar 01, 2025 am 01:37 AM

HTTP Debugging with Node and http-console

jquery add scrollbar to div jquery add scrollbar to div Mar 01, 2025 am 01:30 AM

jquery add scrollbar to div

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

Custom Google Search API Setup Tutorial

See all articles