[英]How to manipulate the pattern of a RegExp dynamically?
我有一个文本lines
数组和一个terms
数组,每个term
行包含一对单词。 例如, terms
数组可能类似于:
blue, red
high, low
free, bound
...
对于数组中的每一行lines
,我需要经过所有的列表terms
,并替换为第二个字的第一个字的每次出现; 全局且不区分大小写。 例如,线
The sky is Blue and High, very blue and high, yet Free
会成为
The sky is red and low, very red and low, yet bound
像这样的代码:
function filter(lines,terms){
for (line of lines){
for (term of terms){
tofind = term[0]; //this is a string not RegExp
//still needs the 'gi' flags
toreplace = term[1];
line = line.replace(tofind,toreplace);
}
}
}
这是错误的,因为tofind
必须是RegExp(模式,'gi'),并且需要在循环内的每次迭代中动态生成。
如果tofind
字符串是静态的,我们可以这样做:
line = line.replace(/some-static-text-here/gi,toreplace)
我尝试了line.replace(new RegExp(tofind,'gi'),toreplace)
但这引发了错误Invalid regular expression: /*Contains/: Nothing to repeat
line.replace(new RegExp(tofind,'gi'),toreplace)
Invalid regular expression: /*Contains/: Nothing to repeat
因此,问题是:如何在循环内动态修改RegExp对象的模式?
如果terms数组仅包含字母数字值,则可以构建新的正则表达式。
function filter(lines, terms) { return lines.map(s => terms.reduce((r, t) => r.replace(new RegExp(t[0], 'gi'), t[1]), s)); } console.log(filter(['The sky is Blue and High, very blue and high, yet Free'], [['blue', 'red'], ['high', 'low'], ['free', 'bound']]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.