1

I have an array that looks like this:

const list = [["GET", /github/g]];

It's an array with a sub array, index 0 having a string, index 1 having a regular expression.

I'm trying to do something like this:

function checkList() {
    return list.find(i => i[0] === "GET" && i[1].test("github.com"));
}

Which I would expect to return the list it finds every time, but that's not the case, it flips back and forth from returning the list and returning undefined.

Here's an example:

let i = 1;
const list = [["GET", /github/g]];
while (i <=10) {
    console.log(list.find(i => i[0] === "GET" && i[1].test("github.com")))
    i++
}

In this example I just loop through it and log the results to show that it returns the list and undefined every other time. What's going on here?

1 Answer 1

1

This is happening because the RegExp in i[1] is actually stateful. Your code calls i[1].test(...) on odd iterations, matching against "github" in "github.com", and advancing lastIndex. Then, on the next even iteration, the next call to test fails to find another match, reaching the end of the string. After that, the RegExp restarts the search from the beginning of the string.

If you would just like to check whether the pattern is found at least once, you could simply remove the /g flag at the end.

From MDN docs:

As with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match.

(See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test)

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

4 Comments

As an another solution, he might need to use string.match(regex) instead.
True, although, I don't immediately see a need for a global match in this case anyway. I'd lean more towards not using features that aren't necessary.
I'm building a library that other people are going to use, so I can't just remove the /g because that might be something that someone wants to use in a url pattern. However, @QuyetNguyen 's solution of changing it to be match appeared to do the trick. Thank you.
@QuyetNguyen, you should probably post it as an answer

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.