1

I have an array of words e.g. apple, banana, horse which I want to have in a later function as split points.

I found this how to concat regex expressions, but it is for a fixed number of expressions: How can I concatenate regex literals in JavaScript?

Question: How to join an array of regex expressions?

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);
Community
  • 1
  • 1
Andi Giga
  • 3,744
  • 9
  • 38
  • 68

2 Answers2

3

You don't need to construct RegExp inside loop just keep pushing strings into temp array and then use join only once outside to construct RegExp object:

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Just a note that `filter = new RegExp(filterTemp.source.join("|"), "gi");` should be `filter = new RegExp(filterTemp.join("|"), "gi");` – Ryan Killeen Dec 07 '15 at 21:37
1

In 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;
}
Gormonn
  • 31
  • 5