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 ] );
}
} 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:
Where it should be abcd{Gefgh{Yijkl
Anyone know what's wrong now?
You can use regexes to remove the ANSI escape sequences from a string in Python. Simply substitute the escape sequences with an empty string using re. sub(). The regex you can use for removing ANSI escape sequences is: '(\x9B|\x1B\[)[0-?]
The code containing only 0 (being \x1B[0m ) will reset any style property of the font. Most of the time, you will print a code changing the style of your terminal, then print a certain string, and then, the reset code.
You can use octal codes in both strings and regexps
x = "\033[1mHello Bold World!\033[0m\n";
x = x.replace(/\033\[[0-9;]*m/,"");
print(x);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With