开发者

How to remove / replace ANSI color codes from a string in Javascript

开发者 https://www.devze.com 2023-03-30 01:17 出处:网络
I have trouble finding the problem with the function below. The first parameters is a string containing ANSI

I have trouble finding the problem with the function below. The first parameters is a string containing ANSI color codes and the second parameter is a boolean.

If the boolean is set to false, a full remove is made on the string.

If the boolean is set to true, a loop convert every color codes into something easier for me to parse later.

I suspect the RegExp being the problem as it is confused between 1;33 and 0;31 for some reason.

var colorReplace = function( input, replace ) {
        var replaceColors = {
            "0;31" : "{r",
            "1;31" : "{R",

            "0;32" : "{g",
            "1;32" : "{G",

            "0;33" : "{y",
            "1;33" : "{Y",

            "0;34" : "{b",
            "1;34" : "{B",

            "0;35" : "{m",
            "1;35" : "{M",

            "0;36" : "{c",
            "1;36" : "{C",

            "0;37" : "{w",
            "1;37" : "{W",

            "1;30" : "{*",

            "0" : "{x"
        };

        if ( replace )
        {
            for( k in replaceColors )
            {
                //console.log( "\033\[" + k + "m" + replaceColors[ k ] );
                var re = new RegExp( "\033\[[" + k + "]*m", "g" );

                input = input.replace( re, replaceColors[ k ] )开发者_StackOverflow社区;
            }
        } else {
            input = input.replace( /\033\[[0-9;]*m/g, "" );
        }

        return input;
    };

console.log( "abcd\033[1;32mefgh\033[1;33mijkl\033[0m" );
console.log( colorReplace( "abcd\033[1;32mefgh\033[1;33mijkl", true ) );

The actual output is:

How to remove / replace ANSI color codes from a string in Javascript

Where it should be abcd{Gefgh{Yijkl

Anyone know what's wrong now?


You can use octal codes in both strings and RegExps

x = "\033[1mHello Bold World!\033[0m\n";
x = x.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"");
print(x);

This matches most ANSI escape codes, including extended VT100 codes, archaic/proprietary printer codes, and so on.


Your Regex was wrong. It should be "\\033\\[" + k + "m", not "\033\[[" + k + "]*m".

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号