0

function abc(regexAsParam){
    xyz(regexAsParam)
}

function xyz(re){
    let regexResult1 = re.test("foo bar") //true
    let regexResult2 = re.test("foo bar") //false
    let regexResult3 = re.test("foo bar") //true
    let regexResult4 = re.test("foo bar") //false
    let regexResult5 = re.test("foo bar") //true
    let regexResult6 = re.test("foo bar") //false
    let regexResult7 = re.test("foo bar") //true
    let regexResult8 = re.test("foo bar") //false
    let regexResult9 = re.test("foo bar") //true

    console.log(`regexResult1:`, regexResult1);
    console.log(`regexResult2:`, regexResult2);
    console.log(`regexResult3:`, regexResult3);
    console.log(`regexResult4:`, regexResult4);
    console.log(`regexResult5:`, regexResult5);
    console.log(`regexResult6:`, regexResult6);
    console.log(`regexResult7:`, regexResult7);
    console.log(`regexResult8:`, regexResult8);
    console.log(`regexResult9:`, regexResult9);

}

abc(/foo/ig)

To my surprise, I found that running this simple code results in a strange alternating pattern of outputs (true, false, true...), even though each line of code in xyz() is identical!

Why is this happening? What can I do to avoid it? Is this a bug in JavaScript?

I tried running this code on multiple browsers and found inconsistent results (never worked in V8 - Node/Chrome, but sometimes worked normally in Safari depending on the computer even when both computers have the same OS and browser version).

In case it's not obvious, this is an extremely distilled version of my code that is just enough to demonstrate the error. It took me a lot of time to find exactly where the error was, but as you can see from the example, the error occurs whenever a regular expression is passed into a javascript function and then passed to another function, or when passed to the function itself if the function is recursive.

NOTE: The error only tends to occur when the i flag is used in the regex!

Btw, the original function where I noticed the error was recursive, but this example I wrote where one function calls another makes it easier to demonstrate the error and to reason about it.

davidnagli
  • 659
  • 1
  • 6
  • 12

0 Answers0