我有一个包含颜色转义序列的字符串,如下所示:
"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);
}
因此,我得到了想要搜索的转义序列,然后使用正则表达式从该序列中获取数字,以构造另一个用于搜索转义序列的正则表达式。难道就没有更简单、更好的方法吗?
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?
发布评论
评论(2)
如果你的问题是我所认为的,我认为更简单更好的方法就是转义你的模式并将其直接传递给 RegExp 构造函数,如我的这个老问题所示
如何在不需要转义所有内容的情况下进行全局字符串替换?
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?
OP 中的原始解决方案非常有效,并且在我看来只有两个问题。
"code = ..."
语句需要一个var
- 按原样它会污染全局命名空间。"code = ..."
语句需要一些错误检查来处理错误的sequence
输入。以下是我改进它的方法:
The original solution in the OP is quite efficient and has only two problems as I see it.
"code = ..."
statement needs avar
- As-is it is polluting the global namespace."code = ..."
statement needs some error checking to handle badsequence
input.Here's how I'd improve it: