1

Possible Duplicate:
javascript string exec strange behavior

I have a regex and i am using like this

new_regex = /^[+-]?(\d+).*\s+(\d+).*\s+([\d\.]+)/g

>>  /^[+-]?(\d+).*\s+(\d+).*\s+([\d\.]+)/g

myregex = new RegExp(new_regex)

>> /^[+-]?(\d+).*\s+(\d+).*\s+([\d\.]+)/g

subject = "+39° 44' 39.28\""
>>  "+39° 44' 39.28""

Above works for every other time i execute following:

myregex.exec(subject)
>> ["+39° 44' 39.28", "39", "44", "39.28"]

second time when i execute it gives null

 myregex.exec(subject)
 >> null
Community
  • 1
  • 1
hitesh israni
  • 1,742
  • 4
  • 25
  • 48
  • This answers your question http://stackoverflow.com/questions/1520800/why-regexp-with-global-flag-in-javascript-give-wrong-results – Phil Parsons Jul 30 '12 at 18:28
  • 1
    @PhilParsons there is no mention in that answer that it's the `g` flag in the regex that causes this `.exec` behavior. The one apsillers posted just as I wrote this is much better – Esailija Jul 30 '12 at 18:38
  • @Esailija no but the question asked is "Why RegExp with **global** flag in Javascript give wrong results?" – Phil Parsons Jul 30 '12 at 19:39

1 Answers1

4

Yes, that's how .exec works with the global flag. If you pass it the same subject, it will advance to the next match, until it finds no matches and returns null:

var str = "1111",
    re = /1/g;


re.exec(str); //["1"]
re.exec(str); //["1"]
re.exec(str); //["1"]
re.exec(str); //["1"]
re.exec(str) // null

You can reset it by changing the subject before execing again:

re.exec("") //Will reset it.

Example of reset:

var str = "1111",
    re = /1/g;

re.exec(str); //["1"]
re.exec(str); //["1"]
re.exec(""); //Reset
re.exec(str); //["1"]
re.exec(str); //["1"]
re.exec(str); //["1"]
re.exec(str); //["1"]
re.exec(str) // null
Esailija
  • 138,174
  • 23
  • 272
  • 326