从字符串中删除所有ANSI颜色/样式 [英] Remove all ANSI colors/styles from strings
问题描述
我使用库将ANSI颜色/样式添加到字符串中。例如:
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'
当我这样做时:
console.log('\u001b[1m\u001b[38;5;231mHello World\u001b[0m\u001b[22m')
a Hello World
将输出白色和粗体信息。
a "Hello World"
white and bold message will be output.
有一个字符串,如'\ u001b [1m \ u001b [38; 5; 231mHello World\\\ [0m\\\ [22m'
如何删除这些元素?
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...
推荐答案
/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g
这匹配大部分 ANSI转义码,不仅仅是颜色,包括扩展的VT100代码,古老/专有的打印机代码等。
This matches most of the ANSI escape codes, beyond just colors, including the extended VT100 codes, archaic/proprietary printer codes, etc.
请注意,上述正则表达式中的 \\\
可能不适用于您的特定库(即使它应该);查看我的答案,了解有关可接受的转义字符的类似问题,如果它没有' t。
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.
如果您不喜欢正则表达式,您可以随时使用 strip-ansi
包。
If you don't like regexes, you can always use the strip-ansi
package.
例如,下面的字符串 jumpUpAndRed
包含用于跳转到上一行的ANSI代码,写一些红色文本,然后返回到下一行的开头 - 其中需要 m
以外的后缀。
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);
这篇关于从字符串中删除所有ANSI颜色/样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!