1

2nd calls to a function using test() with regex is returning different results for some reason. I can't see what is causing the difference. I thought maybe it had something to do with object reference, but can't trace it.

If I change the function to use match() (See second function matchTrees() ). It works find for both the first and second call to the function. Snippet with console output below.

var trees = [
    {"regX" : /alder$/gi,"id":"Alder"},
    {"regX" : /elm/gi,"id":"Elm"},
    {"regX" : /ash/gi,"id":"Ash"}
    ];

function testTrees(treeArray){
    var matchedTrees = [];
    var i, j;
    for (i = 0; i < treeArray.length; i++) { 
        for (j = 0; j < trees.length; j++) {
             if(trees[j].regX.test(treeArray[i])){
             //if(treeArray[i].match(trees[j].regX)){
                matchedTrees.push(trees[j]);

                break;    
            }    
        }        
    }
    return matchedTrees;
}

function matchTrees(treeArray){
    var matchedTrees = [];
    var i, j;
    for (i = 0; i < treeArray.length; i++) { 
        for (j = 0; j < trees.length; j++) {
             //if(trees[j].regX.test(treeArray[i])){
             if(treeArray[i].match(trees[j].regX)){
                matchedTrees.push(trees[j]);

                break;    
            }    
        }        
    }
    return matchedTrees;
}

var treeArray = ["Elm", "Ash"];
var firstresult;
var secondresult;

console.log("run twice with test()");
firstresult = testTrees(treeArray);
console.log(JSON.stringify(firstresult));

secondresult = testTrees(treeArray);
console.log(JSON.stringify(secondresult));

console.log("run twice with match()");
firstresult = matchTrees(treeArray);
console.log(JSON.stringify(firstresult));

secondresult = matchTrees(treeArray);
console.log(JSON.stringify(secondresult));
<!DOCTYPE html>
<html>

  <head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
  </head>

  <body>
  </body>

</html>
seablue
  • 25
  • 2
  • 7
  • That looks like the index with the global flag was the problem - thanks. Interesting that match() treats the global flag differently. – seablue Apr 29 '17 at 10:28

0 Answers0