Search code examples
javascriptnode.jscolorshexansi-escape

Convert base 10 colors OR hex colors to ANSI colors in JavaScript?


The title pretty much says it all. I need to know a way I can convert either base 10 colors OR hex colors to ANSI colors that I can use in the terminal (for example \u001b[31m which is red in ANSI colors).

Either a JavaScript solution or a JS library would be great!


Solution

  • Looking at ANSI Escape Codes I am seeing a way to use RGB colors in ANSI, so you can create a function that takes hex colors and converts them to RGB, and I'm assuming by base 10 colors you already mean RGB So we can check to see if we have a hex color by seeing if the first character is a "#"

    if (color.toString()[0] == "#") { /* then you have yourself a hex color, let's make it RGB*/ }
    function hexToRGB(color) {
        color = color.toString();
        var r = parseInt(color.substring(1, 3), 16);
        var g = parseInt(color.substring(3, 5), 16);
        var b = parseInt(color.substring(5, 7), 16);
        return `rgb(${r}, ${g}, ${b})`;
    }
    

    So after that you will have your RGB (assuming your hex color is in the form of #FFFFFF)

    Use this as a guide to take your RGB string and format it into an ANSI Escape Code: Use this as a guide to take your RGB string and format it into an ANSI Escape Code