1

I have such function:

function validateData( value, rule ){
    var re = new RegExp( rule, 'gi' );
    alert(re.test( value ));
    return re.test( value );
}

Alert shows me true, but when I call this function:

alert(validateData( value, regExp ));

alert shows me false. Why?

Dmytro Zarezenko
  • 10,526
  • 11
  • 62
  • 104
  • if you comment out the alert, what it returns? I think it has something to do with how `RegExp` is working (probably `lastIndex` property is already set after first call) – Catalin Jul 17 '14 at 09:06
  • 1
    Alerts `true` twice here - http://jsfiddle.net/7kCdX/ – Nikola Dimitroff Jul 17 '14 at 09:11
  • It's a bug in the regex engine in ecmascript, when you call `test` on certain RegExp expressions you modify the RegExp object, so it works the first time, then not the next time etc. Common issue. – adeneo Jul 17 '14 at 09:15
  • Funny - few console.log(re.test( value )); return true next bt one – Evgeniy Jul 17 '14 at 09:19
  • @adeneo, is it some 'magic' modification, as i dont see any differences in console.log between .test cals ? – Evgeniy Jul 17 '14 at 09:21
  • @Evgeniy - no magic -> **http://jsfiddle.net/7kCdX/1/** – adeneo Jul 17 '14 at 09:26
  • 1
    http://stackoverflow.com/questions/3891641/regex-test-only-works-every-other-time – adeneo Jul 17 '14 at 09:31
  • 1
    @NikolaDimitroff: Try some regex that does not match the empty string. – Bergi Jul 17 '14 at 09:31

0 Answers0