Laman

Showing posts with label Converter. Show all posts
Showing posts with label Converter. Show all posts

Converter Hex to RGB and RGB to Hex


this function for convert Hex to RGB
function hexToRgb() {

  // Get the value from input text

    var hex = document.getElementById("hex").value;

  // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
    var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, function(m, r, g, b) {
        return r + r + g + g + b + b;
    });
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    var rgb = "rgb("+parseInt(result[1], 16)+","+parseInt(result[2], 16)+","+parseInt(result[3], 16)+")";
  // Return value

    return rgb;
}


this function for convert RGB to Hex
function rgbToHex() {

  // Get value from input text
    var rgb = document.getElementById("rgb").value;

  // Remove all character and get the number
    rgb = rgb.replace(/[a-zA-Z()]+/g, "");

  // Split the string
    var res = rgb.split(",");

  // Get the individual value and set the hex
    var r = parseInt(res[0]).toString(16);
    var g = parseInt(res[1]).toString(16);
    var b = parseInt(res[2]).toString(16);

  // If result length == 1 add the 0 number
    r = r.length == 1 ? "0" + r : r;
    g = g.length == 1 ? "0" + g : g;
    b = b.length == 1 ? "0" + b : b;

  // Return value
    return "#"+r+g+b;
}


Result
See the Pen Converter Hex RGB by Hangs Breaker (@hangsbreaker) on CodePen.