1

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.

2
  • 1
    The actual issue here is the reg.test() closing round bracket. It should go after ] and not after true: if (reg.test(elements[i]) == true) { Commented Mar 22, 2017 at 14:51
  • This sounds very much like a duplicate of Why RegExp with global flag in Javascript give wrong results, but there are so many other issues here... Commented Mar 22, 2017 at 23:51

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.