.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:
JavaScript
x
7
1
{
2
text: Check.string()
3
.regularExpression(/reg1/)
4
.regularExpression(/reg2/)
5
.regularExpression(/reg3/)
6
}
7
Advertisement
Answer
You can use the reduce
method:
JavaScript
1
5
1
const regex = ['reg1', 'reg2', 'reg3'];
2
{
3
text: regex.reduce((check, regex) => check.regularExpression(new RegExp(regex)), Check.string())
4
}
5
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:
JavaScript
1
9
1
let check = Check.string();
2
for (const item of regex) {
3
check = check.regularExpression(new RegExp(regex));
4
}
5
6
{
7
text: check
8
}
9