rtheunissen
rtheunissen

Reputation: 7435

Javascript number regex test failing - can't figure out why

Here's a jsFiddle: jsFiddle

Relevant code:

var number = /\d+(.\d+)?/g;

$('body').append(number.test(2.5) + "<br>");
$('body').append(number.test(20) + "<br>");
$('body').append(number.test(2) + "<br>");

Output

true
false
true

Upvotes: 0

Views: 100

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191749

Get rid of the g. It's not needed, and it causes the regex to fail because the RegExp object keeps track of its position based on the previous match: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/test

As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match.

http://jsfiddle.net/BUpyd/1/

Upvotes: 7

Related Questions