Skip to content

Instantly share code, notes, and snippets.

@Rich-Harris
Last active December 28, 2015 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rich-Harris/7544330 to your computer and use it in GitHub Desktop.
Save Rich-Harris/7544330 to your computer and use it in GitHub Desktop.
A regular expression that matches any legal JavaScript number, including weird edge cases. If you have a failing test case, let me know!
var pattern = /(?:[+-]?)0*(?:(?:(?:[1-9]\d*)?\.\d+)|(?:(?:0|[1-9]\d*)\.)|(?:0|[1-9]\d*))(?:[eE][+-]?\d+)?/;
var shouldPass = [
'0',
'00',
'000123',
'0.01',
'1',
'-0',
'+1',
'1.234',
'.234',
'-.234',
'-0.234',
'4.'
];
var shouldFail = [
'',
'.',
'foo',
'0.1.2',
'1,234'
];
shouldPass.forEach( function ( testcase ) {
var match = pattern.exec( testcase );
console.assert( match && testcase === match[0], '"' + testcase + '"' );
});
shouldFail.forEach( function ( testcase ) {
var match = pattern.exec( testcase );
console.assert( !match || testcase !== match[0], '"' + testcase + '"' );
});
@Rich-Harris
Copy link
Author

NB: this doesn't include hex numbers, and it allows signs before numbers (which isn't technically part of ECMA-262 but would be a nuisance to omit).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment