Regular expression containing an escape sequence in JavaScript

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?


  • If your problem is what I think it i, I think the easier and nicer way is just escaping your pattern and passing it directly to the RegExp constructor, as seen in this old question of mine

    How do I do global string replace without needing to escape everything?

    function escape(s) {
        return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
    function replace_all(str, pattern, replacement){
        return str.replace( new RegExp(escape(pattern), "g"), replacement);
    replace_all(my_text, "\x1b[33m", "REPLACEMENT")