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);
1
  • filterTemp.push(new RegExp("\\b" + word + "\\b")); Commented Mar 24, 2015 at 9:25

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Just a note that filter = new RegExp(filterTemp.source.join("|"), "gi"); should be filter = new RegExp(filterTemp.join("|"), "gi");
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.