user7280974
user7280974

Reputation:

Regex doesn't return true in a loop

I wrote simple regex to check few words and then put them into an new array. Everything works fine, when I check values manually, but when I put it into loop, I receive false. My question is - why? I think there's something wrong in my if statement, but for me it's ok... Here's my code:

var elements = ["sztuka", "sztuki", "sztuk", "sztukateria", "sztukmistrz", "sztuczka"];
var correctElements = [];
var reg = /^sztuk[ia]$/ig;

function checkElements(reg, elements) {
    for (var i=0; i < elements.length; i++) {
        if (reg.test(elements[i] == true)) {
            correctElements.push(elements[i]);
         } else {
             return false;
         }
    }

    console.log(correctElements);
}

When I check it manualy I receive true:

var reg = /^sztuk[ia]$/ig;
console.log(reg.test(elements[0]));

I would be very grateful if you could help me with that and explain why it's happening.

Upvotes: 1

Views: 224

Answers (2)

VHS
VHS

Reputation: 10184

You shouldn't return false until you iterate through all the items. Check the following working snippet.

var elements = ["sztuka", "sztuki", "sztuk", "sztukateria", "sztukmistrz", "sztuczka"];
var correctElements = [];
var reg = /^sztuk[ia]$/ig;
checkElements(reg,elements);

function checkElements(reg, elements) {
    console.log("hi");
    for (var i=0; i < elements.length; i++) {
        if (reg.test(elements[i]) == true) {
            correctElements.push(elements[i]);
        }
    }

    console.log(correctElements);
}

Upvotes: 0

jdmdevdotnet
jdmdevdotnet

Reputation: 1

reg.test(elements[i] == true) need to be reg.test(elements[i]) == true)

Upvotes: 1

Related Questions