Reputation: 305
I am creating a javascript(Node.js) looping function that is supposed to iterate through an array of strings, then return true or false when tested against a regular expression. If FALSE, return the value immediately (breaking the loop). However, the second value in the array still returns false, although it is valid.
The calling function passes these values:
var valuesArray = ["ABCXYZ", "ABCXYZ1"];
var regexValue = /[a-zA-Z0-9]+$/;
var regex = new RegExp(regexValue);
function validateArrayValues(valuesArray, regex) {
var regexResult, item;
for (let counter = 0; counter < valuesArray.length; counter++) {
item = valuesArray[counter];
regexResult = regex.test(item);
if (!regexResult) return false;
}
return true;
}
Upvotes: 0
Views: 138
Reputation: 755
Work correctly, anything else you removed to keep the example simple?
var valuesArray = ["ABCXYZ", "ABCXYZ1"];
var regexValue = /[a-zA-Z0-9]+$/;
var regex = new RegExp(regexValue);
function validateArrayValues(valuesArray, regex) {
var regexResult, item;
for (let counter = 0; counter < valuesArray.length; counter++) {
item = valuesArray[counter];
regexResult = regex.test(item);
if (!regexResult) return false;
}
return true;
}
console.log(validateArrayValues(valuesArray, regex));
Upvotes: 1