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.

  • 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) {` – Dmitry Egorov Mar 22 '17 at 14:51
  • This sounds very much like a duplicate of [Why RegExp with global flag in Javascript give wrong results](http://stackoverflow.com/questions/1520800/why-regexp-with-global-flag-in-javascript-give-wrong-results), but there are so many other issues here... – Bergi Mar 22 '17 at 23:51

2 Answers2

1

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

jdmdevdotnet
  • 1
  • 2
  • 19
  • 50
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);
}
VHS
  • 9,534
  • 3
  • 19
  • 43