0
let phoneNums = ["801-766-9754", "801-545-5454", "435-666-1212", "801-796-8010", "435-555-9801", "801-009-0909", "435-222-8013", "801-777-66553", "801-777-665-", "801-77A-6655", "801-778-665"];

let regEx = /801-/g, 
    newArray = []
newArray = phoneNums.map(elem => regEx.test(elem));
console.log(newArray);

Well...The question is is why when enabling global search, we do not get the result we want. The expected result should be

​[ true, true, false, true, false, true, false, true, true, true, true]

But with the global search or g flag enabled, the result is

[ true, false, false, true, false, true, false, true, false, true, … ]

So I am just wondering why it is that?

  • Looking at your expected result, you're looking for something to match at start of string, you can use `startsWith('801-')` or `/^801-/` – Code Maniac Aug 24 '19 at 04:24

1 Answers1

2

This is because JavaScript Regexes are stateful.

When you call test, it changes the state of the regex (advances it to the end of the match). When you call it the second time (on the next element of the array), it tries to search starting from the end of the previous match. It results in false because there are no more matches after the first match.

This can be demonstrated by this simple code:

let phoneNum = "801-545-5454";

let regEx = /801-/g;
console.log(regEx.test(phoneNum));
console.log(regEx.test(phoneNum));

One way to do this is to not save the regex into a variable:

let phoneNums = ["801-766-9754", "801-545-5454", "435-666-1212", "801-796-8010", "435-555-9801", "801-009-0909", "435-222-8013", "801-777-66553", "801-777-665-", "801-77A-6655", "801-778-665"];

let newArray = phoneNums.map(elem => /801-/g.test(elem));
console.log(newArray);

Also note that since you are just testing for whether the string matches a regex, you don't need the g modifier, because it doesn't matter whether your string matches it once or 100 times.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • IMO `g` doesn't makes sense in the last example, it can be safely dropped, since test results in boolean value, so even if it matches once or more than once it will not make any difference, anways your answer explain the actual problem +1 – Code Maniac Aug 24 '19 at 04:26
  • @CodeManiac Yeah, good point. – Sweeper Aug 24 '19 at 04:28