Remove all ANSI colors/styles from strings

前端 未结 2 681
眼角桃花
眼角桃花 2020-12-14 07:03

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\'
&g         


        
相关标签:
2条回答
  • 2020-12-14 08:04

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

    0 讨论(0)
  • 2020-12-14 08:08

    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, '')
    
    0 讨论(0)
提交回复
热议问题