I have a string containing colour escape sequences, like that:
"white text \x1b[33m yellow text \x1b[32m green text"
Now I need to replace all occurences of a certain escape sequence. I only get the escape sequence I shall look for, that's what I have. As far as I know, the only way in JavaScript to replace all occurences of something is to use regular expressions.
// replace all occurences of one sequence string with another
function replace(str, sequence, replacement) {
// get the number of the reset colour sequence
code = sequence.replace(/\u001b\[(\d+)m/g, '$1');
// make it a regexp and replace all occurences with the start colour code
return str.replace(new RegExp('\\u001b\\[' + code + 'm', 'g'), replacement);
}
So, I am getting the escape sequence I want to search for, then I use a regular expression to get a number out of that sequence just to construct another regular expression that would search for the escape sequence. Isn't there an easier, nicer way?