Remove all ANSI colors/styles from strings

旧时模样 提交于 2019-11-29 06:00:50

问题


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...


回答1:


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);



回答2:


The escape character is \u001b, and the sequence from [ until first m is encountered is the styling. You just need to remove that. So, replace globally using the following pattern:

/\u001b\[.*?m/g

Thus,

'\u001b[1m\u001b[38;5;231mHello World\u001b[0m\u001b[22m'.replace(/\u001b\[.*?m/g, '')


来源:https://stackoverflow.com/questions/25245716/remove-all-ansi-colors-styles-from-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!