gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:01:07 24 4
gpt4 key购买 nike

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com