How to check if a string contains a number in JavaScript?

前端 未结 8 1357
粉色の甜心
粉色の甜心 2021-01-13 18:37

I don\'t get how hard it is to discern a string containing a number from other strings in JavaScript.

Number(\'\') evaluates to 0, while

8条回答
  •  再見小時候
    2021-01-13 18:52

    Let's try

    ""+(+n)===n
    

    which enforces a very rigid canonical way of the number.

    However, such number strings can be created by var n=''+some_number by JS reliable.

    So this solution would reject '.01', and reject all simple numbers that JS would stringify with exponent, also reject all exponential representations that JS would display with mantissa only. But as long we stay in integer and low float number ranges, it should work with otherwise supplied numbers to.

提交回复
热议问题