1

I am looking to format text before passing it to stdout/console. To do this properly I need to know how long a given section of text is after being printed to the console, which requires knowing how much characters will not be printed due to them being escape sequences.

On the web I have found multiple documentations for these sequence commands, but there seems to be no quick and easy way to find out where a given escape sequence command ends unless I was to parse them. Is there a trick/solution to getting the length of any escape sequence command without parsing?

How many characters is this \x1b[38;2;20;60;122m string \x1b[0m in console?
John Smith
  • 570
  • 2
  • 7
  • 17
  • 1
    You don't need to parse them in detail, just search for the end character of the escape sequence. – Barmar Jan 13 '20 at 18:09
  • 1
    What language are you doing this in? https://stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python shows a Python solution. – Barmar Jan 13 '20 at 18:10
  • I am using node.js – John Smith Jan 13 '20 at 18:43
  • There are regular expressions in the other question that filter out the escape sequences. I think they should work in JS. – Barmar Jan 13 '20 at 18:45

1 Answers1

1

You can use ansifilter:

$ printf '\x1b[38;2;20;60;122mabc\x1b[0m'  | ./ansifilter --no-trailing-nl | wc -c
3
Arkadiusz Drabczyk
  • 11,227
  • 2
  • 25
  • 38