Search code examples
javascriptregexterminalansi

JavaScript how to split a string every n characters while ignoring ANSI codes


How would you approach splitting a JavaScript string every n characters while ignoring the ansi codes? (so splitting every n + length of ansi characters contained in that string)

It is important to keep the ansi code in the final array.

I know using regex you'd write something like /.{1,3}/, but how would you ignore the ansi chars in the count?

Example:

Given \033[34mHey \033[35myou\033[0m, how would you split every 3 chars to get:

[
  '\033[34mHey',
  ' \033[35myo',
  'u\033[0m'
]

Solution

  • Here is a way to achieve what you need:

    s = "\033[34mHey \033[35myou\033[0mfd\033[1m";
    chunks = s.match(/(?:(?:\033\[[0-9;]*m)*.?){1,3}/g);
    var arr = [];
    [].forEach.call(chunks, function(a) {
        if (!/^(?:\033\[[0-9;]*m)*$/.test(a)) {
    		arr.push(a);
        }
    });
    document.getElementById("r").innerHTML = JSON.stringify(arr);
    <div id="r"/>

    Note that octal codes can be used directly in the regex. We filter all the empty and ANSI-color code only elements in the forEach call.