5

http://jsfiddle.net/bpt33/

var t = "";

var a = ["atom-required","atom-label","atom-data-type","atom-regex"];

var r = /atom\-(label|required|regex|data\-type|class|is\-valid|field\-value|error)/i;

function test(a, r){
    for(var i = 0; i<a.length; i++){
        t += a[i] + " => " + r.test(a[i]) + "<br/>";
    }
}

test(a, r);

t += "<br/>";

a = ["atom-required","atom-label","atom-data-type","atom-regex"];

var r = /atom\-(label|required|regex|data\-type|class|is\-valid|field\-value|error)/gi;

test(a, r);

$("#results").get(0).innerHTML = t;

When g is not specified, it works correctly,

atom-required => true
atom-label => true
atom-data-type => true
atom-regex => true

When g is specified, it works alternatively

atom-required => true
atom-label => false
atom-data-type => true
atom-regex => false
Akash Kava
  • 39,066
  • 20
  • 121
  • 167
  • As a side note, there's no need to escape `-` - it's only special in a character class. – georg Jun 09 '13 at 20:26
  • possible duplicate of [Why RegExp with global flag in Javascript give wrong results?](http://stackoverflow.com/questions/1520800/why-regexp-with-global-flag-in-javascript-give-wrong-results) – Bergi Jul 09 '13 at 16:45

1 Answers1

11

Because with the g modifier, the regexp becomes stateful, and resumes the next search at the index after the last match.

When no match is found, it resets itself.

You can observe the starting point by using the .lastIndex property.

r.lastIndex; // 0 or some higher index

You can reset it manually by setting that property to 0.

r.lastIndex = 0
georg
  • 211,518
  • 52
  • 313
  • 390
  • "When no match is found, it resets itself" and returns false – thejh Jun 09 '13 at 20:05
  • @thejh: Yes, the `test()` method naturally returns `false` when no match is found. –  Jun 09 '13 at 20:06
  • 1
    Actually, it makes very little (close to zero, I'd say) sense using `/g` modifier on the pattern that is to be used in `.test` - unless you indeed want the regex to advance. But that's VERY rare, to say the least. – raina77ow Jun 09 '13 at 20:06
  • 2
    @raina77ow: Unless you want to test for multiple matches on the same string in a loop, and stop the testing when a certain quantity is found. –  Jun 09 '13 at 20:08