Last active
December 28, 2015 18:39
-
-
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!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 + '"' ); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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).