Вместо одного RE, рассмотрите возможность проверки букв и цифр отдельно, с глобальным флагом, и проверьте, равна ли длина массива глобального соответствия n
и m
соответственно:
let n = 2,
m = 3; // example n and m values
let s = ["32abc", "abc32", "a3b2c", "3abc2", "a2", "abcd23", "a2b3c4", "aa", "32"];
let r = s.map(str => (
/^[0-9a-z]*$/.test(str) &&
(str.match(/[0-9]/g) || []).length <= n &&
(str.match(/[a-z]/g) || []).length <= m
));
console.log("current is:", JSON.stringify(r));
console.log("shoud be: [true,true,true,true,true,false,false,true,true]");
Или, чтобы быть более многословным, но, возможно, более элегантным, без создания пустого промежуточного массива:
let n = 2,
m = 3; // example n and m values
let s = ["32abc", "abc32", "a3b2c", "3abc2", "a2", "abcd23", "a2b3c4", "aa", "32"];
let r = s.map((str, i) => {
const numMatch = str.match(/[0-9]/g);
const numMatchInt = numMatch ? numMatch.length : 0;
const alphaMatch = str.match(/[a-z]/g);
const alphaMatchInt = alphaMatch ? alphaMatch.length : 0;
return numMatchInt <= n && alphaMatchInt <= m && /^[0-9a-z]*$/.test(str);
});
console.log("current is:", JSON.stringify(r));
console.log("shoud be: [true,true,true,true,true,false,false,true,true]");