Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all ANSI colors/styles from strings

I use a library that adds ANSI colors / styles to strings. For example:

> "Hello World".rgb(255, 255, 255) '\u001b[38;5;231mHello World\u001b[0m' > "Hello World".rgb(255, 255, 255).bold() '\u001b[1m\u001b[38;5;231mHello World\u001b[0m\u001b[22m' 

When I do:

console.log('\u001b[1m\u001b[38;5;231mHello World\u001b[0m\u001b[22m') 

a "Hello World" white and bold message will be output.

Having a string like '\u001b[1m\u001b[38;5;231mHello World\u001b[0m\u001b[22m' how can these elements be removed?

foo('\u001b[1m\u001b[38;5;231mHello World\u001b[0m\u001b[22m') //=> "Hello World" 

Maybe a good regular expression? Or is there any built-in feature?


The work around I was thinking was to create child process:

require("child_process")  .exec("node -pe \"console.error('\u001b[1m\u001b[38;5;231mHello World\u001b[0m\u001b[22m')\""  , function (err, stderr, stdout) { console.log(stdout);  }); 

But the output is the same...

like image 689
Ionică Bizău Avatar asked Aug 11 '14 14:08

Ionică Bizău


People also ask

How do I delete ANSI characters?

You can use regexes to remove the ANSI escape sequences from a string in Python. Simply substitute the escape sequences with an empty string using re. sub(). The regex you can use for removing ANSI escape sequences is: '(\x9B|\x1B\[)[0-?]


1 Answers

The regex you should be using is

/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g 

This matches most of the ANSI escape codes, beyond just colors, including the extended VT100 codes, archaic/proprietary printer codes, etc.

Note that the \u001b in the above regex may not work for your particular library (even though it should); check out my answer to a similar question regarding acceptable escape characters if it doesn't.

If you don't like regexes, you can always use the strip-ansi package.


For instance, the string jumpUpAndRed below contains ANSI codes for jumping to the previous line, writing some red text, and then going back to the beginning of the next line - of which require suffixes other than m.

var jumpUpAndRed = "\x1b[F\x1b[31;1mHello, there!\x1b[m\x1b[E";  var justText = jumpUpAndRed.replace(      /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '');  console.log(justText);
like image 181
Qix - MONICA WAS MISTREATED Avatar answered Oct 09 '22 04:10

Qix - MONICA WAS MISTREATED