我有一系列的词,如苹果,香蕉,马,我想在以后的功能,作为分裂点。
我发现了如何连接regex表达式,但它适用于固定数量的表达式:How can I concatenate regex literals in JavaScript?
问题:如何加入regex表达式数组?
filterTemp = [];
for (i = 0, len = filterWords.length; i < len; i++) {
word = filterWords[i];
filterTemp.push(new RegExp("\b" + word + "\b"));
}
filter = new RegExp(filterTemp.source.join("|"), "gi");
return console.log("filter", filter);发布于 2015-03-24 09:33:55
您不需要在循环中构造RegExp,只需将字符串推入临时数组,然后只在外部使用join一次来构造RegExp对象:
var filterWords = ['abc', 'foo', 'bar'];
var filterTemp = [];
for (i = 0, len = filterWords.length; i < len; i++) {
filterTemp.push("\\b" + filterWords[i] + "\\b");
}
filter = new RegExp(filterTemp.join("|"), "gi");
console.log("filter", filter);
//=> /\babc\b|\bfoo\b|\bbar\b/gi发布于 2022-01-31 11:39:13
2022年:
const validate = (val: string) => {
const errorMessage =
'Enter the time separated by commas. For example: 12:30, 22:00, ... etc.';
const values = val.split(',').map((val: string) => val.trim());
const filter = new RegExp(/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/);
const isValid = values.some(
(value: string) => !filter.test(value),
);
return !isValid || errorMessage;
}https://stackoverflow.com/questions/29228940
复制相似问题