1

I have added the result in the comments after each line. I want to know why they show different results. Specially str3 and str4, which are simillar strings (in this particular context), but for str3 it shows false and for str4 it shows true. Can anyone explain why?

    var regExpr = /sas/g;
    var str = "sassassas";
    var str1 = "sassassa";
    var str2 = "safasassassas";
    var str3 = "fgsassasfg";
    var str4 = "fgsassassasfgdeifk";

    console.log(regExpr.test(str));  //true
    console.log(regExpr.test(str1)); //true
    console.log(regExpr.test(str2)); //true
    console.log(regExpr.test(str3)); //false
    console.log(regExpr.test(str4)); //true
Toto
  • 89,455
  • 62
  • 89
  • 125
  • It's usually because, when you use the global modifier, the last match position is retained with the regex, so that's where it starts the next time you use it. You can reset the position, but it's better that you don't use the global modifier for testing. The reason most folks don't encounter this problem is because their code is scoped so that the regex var is reassigned each time. –  Nov 12 '18 at 19:42
  • 1
    Also, be aware that on a failed match or end of string, the position is automatically set to zero. That's why 3 fails, but 4 passes –  Nov 12 '18 at 19:43
  • @sln I basically know nothing about RE internals, but as I see it, that would mean that changing it to `/sas.*/g` ought to *reset* it, but it doesn't. It makes it T(rue),F(alse),T,F,T. Or am I miss understanding? – SamWhan Nov 12 '18 at 19:59
  • @SamWhan - You're right, it get that result as well. Even with `.*` it does the T,F,T,F thing. –  Nov 12 '18 at 20:30
  • @SamWhan - On the other hand, this works `/^(?=.*sas)/g` and this too `\(?=sas)/g` so it's a position thing I guess. –  Nov 12 '18 at 20:35
  • @SamWhan - Ok, did a test with seven consecutive `console.log(regExpr.test(str));` I got TTTFTTT which says three things. One, `test()` only need 1 match. Two, the next position is 1+end of last match as stored by the regex object. Three, if 1+end of last match >= end of string, _or_, no match it returns false and resets the position. I guess that's all there is. Apparently, the regex object won't preemptively reset the position until it has to actually put the current position there. It doesn't do this if it matches at a position before that. –  Nov 12 '18 at 20:57

0 Answers0