Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ugultopu/bf53821d8f81d4a3e4778dbbefc8f2cf to your computer and use it in GitHub Desktop.
Save ugultopu/bf53821d8f81d4a3e4778dbbefc8f2cf to your computer and use it in GitHub Desktop.

That is, how to make the text that is sent to a terminal bold, italic, give it colors, etc? The answer is using ANSI Escape Sequences. Using the Control Sequence Introducer group of ANSI Escape Sequences, we can style the text that appears on a terminal, on the terminals that support ANSI Escape Sequences.

For example, let's say that we want to make a portion of the text that we print bold. We can do it as follows:

// ANSI escape character
const ESC = '\x1B';
// Control Sequence Introducer
const CSI = `${ESC}[`;
// Select Graphic Rendition (SGR) sequences
const BOLD = `${CSI}1m`;
const RESET = `${CSI}0m`;

// Some text to test the ANSI Escape Sequences
console.log(`${BOLD}Hello.${RESET} How are you?`);

The output should be "Hello. How are you?", with the "Hello." part of the string styled as bold on terminals that support ANSI escape sequences.

Sources

https://mathiasbynens.be/notes/javascript-escapes

@ugultopu
Copy link
Author

Note that escape sequences embedded in object properties won't have any effect.

const ESC = '\x1B';
// Control Sequence Introducer
const CSI = `${ESC}[`;
// Select Graphic Rendition (SGR) sequences
const RED = `${CSI}31m`;
const GREEN = `${CSI}32m`;
const RESET = `${CSI}0m`;

// Works as expected
console.log('Hello' + RED + ' World' + RESET + ' Hello');

// Does not work
const a = {
  x: 'Hello' + RED + ' World' + RESET + ' Hello'
};

console.log(a);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment