简体   繁体   中英

javascript number regular expression

I've come up with this regular expression to validate a javascript number according to the specification:

(-|\+|)(\d+\.?\d*|\.\d+)([eE](-|\+|)\d+)?

As far as I can think of, these are valid numbers in js:

123,123.3, .3, -123, -.3, -.3e-2, -.3e+2, +.2e2... and so forth.

I've been trying to find a verified regular expression on the internet so that I could compare my solution but to no avail.

Could anyone tell me if my approach is correct or give me a better solution?

Link to test my solution

While using isNan is the correct way of checking numbers in JavaScript, you can also validate floating point numbers with [-+]?[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)? regex (taken from Regular-Expressions.info ).

Consider using appropriate anchors though! ( ^ for string start, $ for string end).

Demo is available here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM