javascript - JavaScript 中包含转义序列的正则表达式

标签 javascript regex console coffeescript ansi-escape

我有一个包含颜色转义序列的字符串,就像这样:

"white text \x1b[33m yellow text \x1b[32m green text"

现在我需要替换特定转义序列的所有 出现。我只得到我要寻找的转义序列,这就是我所拥有的。据我所知,在 JavaScript 中替换所有出现的东西的唯一方法是使用正则表达式。

// 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);
}

所以,我得到了我想要搜索的转义序列,然后我使用正则表达式从该序列中获取一个数字,只是为了构造另一个将搜索转义序列的正则表达式。有没有更简单、更好的方法?

最佳答案

如果你的问题和我想的一样,我认为更简单更好的方法就是转义你的模式并将其直接传递给 RegExp 构造函数,如我的这个老问题所示

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")

关于javascript - JavaScript 中包含转义序列的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8530751/

相关文章:

windows - cygwin + console2 : running cygwin bash with startup dir

javascript - 使用javascript启用提交按钮

javascript - res.sendFile 发送静态文件+对象

python - 将字符串分段成数组,正则表达式?

javascript - 在逗号分隔值的文本中捕获逗号

Azure 上的 Linux VM 控制台

javascript - 在 Ajax 中获得响应的问题

javascript - 使用构造函数创建对象数组

java - Ctrl-M 的正则表达式问题

delphi - Delphi 中用于命令提示符的管道