Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavascriptHow to add special characters to text to print in color in...

How to add special characters to text to print in color in the console in JavaScript ?

The purpose of this article is to add special characters to text to print in color in the console in JavaScript.

Approach: The ANSI escape codes help change/specify the color of the output in the console. The color of the output of the console can be changed by adding these escape codes just before the actual text. 

Syntax: 

/*Codes for different Colors*/
black = "\x1b[30m"
red = "\x1b[31m"
green = "\x1b[32m"
yellow = "\x1b[33m"
blue = "\x1b[34m"
magenta = "\x1b[35m"
cyan = "\x1b[36m"
white = "\x1b[37m"

Example : 

Javascript




<script>
  console.log("\x1b[31m"+ "Red");
  console.log("\x1b[32m"+ "Green");
  console.log("\x1b[35m"+ "Magenta");
</script>


Output:

Note: The above task can be simplified by adding a custom helper function in the script which can be invoked with the color and data to be displayed in the console.

Example: The following is the JavaScript code for performing the task using a custom helper function.

Javascript




<script>
function colorHelper(color,data)
{  
  
   /* function receives 2 arguments color and data*/
   const black = "\x1b[30m";  
   const red = "\x1b[31m";
   const green = "\x1b[32m";
   const yellow = "\x1b[33m";
   const blue = "\x1b[34m";
   const magenta = "\x1b[35m";
   const cyan = "\x1b[36m";
   const white = "\x1b[37m";
   const arr=[];
  
   /* Storing the color codes in Array */
   arr[0] = black;  
   arr[1] = red;
   arr[2] = green;
   arr[3] = yellow;
   arr[4] = blue;
   arr[5] = magenta;
   arr[6] = cyan;
   arr[7] = white;
   console.log(arr[color]+data);
}
  
/* colorHelper function called with color and data */
colorHelper(1,"I am Red");  
colorHelper(2,"I am Green");
colorHelper(5,"I am Magenta");
</script>


Output: 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments