0

.regularExpression() is hardcoded 3 times in the script, is there a way to dynamically attach it from loops from variable const regex = ['reg1', 'reg2', 'reg3']?

Usage:

{
       text: Check.string()
                  .regularExpression(/reg1/)
                  .regularExpression(/reg2/)
                  .regularExpression(/reg3/)
}
I'll-Be-Back
  • 10,530
  • 37
  • 110
  • 213
  • [Regular Expressions: Is there an AND operator?](https://stackoverflow.com/questions/469913) – adiga Mar 23 '22 at 10:16
  • @adiga No, I want to keep it separate. It needs to loop from variable. – I'll-Be-Back Mar 23 '22 at 10:17
  • You need to create a regex as mentioned in the linked ticket Something like: `(?=.*reg1)(?=.*reg2)(?=.*reg3)`. So, `const final = ['reg1', 'reg2', 'reg3'].map(str => \`(?=.*${str})\`).join('')` and then `.regularExpression(new RegExp(final ))` – adiga Mar 23 '22 at 10:33

1 Answers1

1

You can use the reduce method:

const regex = ['reg1', 'reg2', 'reg3'];
{
  text: regex.reduce((check, regex) => check.regularExpression(new RegExp(regex)), Check.string())
}

In this way, starting from the initial value Check.string(), you will iteratively chain new regular expressions, accordingly to your array.

Alternatively, you can use a plain for-loop:

let check = Check.string();
for (const item of regex) {
  check = check.regularExpression(new RegExp(regex));
}

{
  text: check
}