Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

javascript - 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 Worldu001b[0m'
> "Hello World".rgb(255, 255, 255).bold()
'u001b[1mu001b[38;5;231mHello Worldu001b[0mu001b[22m'

When I do:

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

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

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

foo('u001b[1mu001b[38;5;231mHello Worldu001b[0mu001b[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[1mu001b[38;5;231mHello Worldu001b[0mu001b[22m')""
 , function (err, stderr, stdout) { console.log(stdout);
 });

But the output is the same...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The regex you should be using is

/[u001bu009b][[()#;?]*(?:[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[Fx1b[31;1mHello, there!x1b[mx1b[E";
var justText = jumpUpAndRed.replace(
    /[u001bu009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '');
console.log(justText);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...