chalk/chalk

chalk.hex(color)(string) does not work as expected when used with string.replaceAll()

eserini opened this issue · 1 comments

Hello,
I found some strange behaviour with chalk and replaceAll on node18 while i was writing a function to integrate chalk with winston.

Ho to reproduce:

const hexColorRe = /\[c#([0-9a-fA-F]{6})]([^\]]+)\[\/c]/g
const message = 'This should be [c#ff0000]RED[/c]'

//First capture $1 is ff0000 and second capture is RED

//Test 1
console.log(message.replaceAll(hexColorRe, chalk.hex('$1')('$2'))

//Test 2
console.log(message.replaceAll(hexColorRe, chalk.hex('#$1')('$2'))

//Test 3
console.log(message.replaceAll(hexColorRe, (m, g1,g2) => chalk.hex(g1)(g2)))

Test 1 & 2 prints black text instead of red
Test 3 prints red text

For further testing i wrote the outputs of chalk.hex into a file with fs.writeFileSync() and what i got for the first two tests is �[38;5;16mRED�[39m, the third one instead correctly returns �[38;5;196mRED�[39m

I also tested bold and italic and the combination of the two and everything works fine, it seems a problem that happens just with hex.

At this point i'm not even sure it's a problem with chalk honestly

Thanks :)

Qix- commented

Err, yeah because that's not how Chalk (or any ANSI escapes) work. Your third test is the only way to make this work.

E.g. there's no way to 'replace' the hex value in this string because that's now how we convert hex down to escaped values.

> chalk.hex('ABCDEF')('test')
'\x1B[38;2;171;205;239mtest\x1B[39m'