(Built-in) way in JavaScript to check if a string is a valid number

前端 未结 30 3859
-上瘾入骨i
-上瘾入骨i 2020-11-22 01:54

I\'m hoping there\'s something in the same conceptual space as the old VB6 IsNumeric() function?

30条回答
  •  旧时难觅i
    2020-11-22 02:17

    You can use the result of Number when passing an argument to its constructor.

    If the argument (a string) cannot be converted into a number, it returns NaN, so you can determinate if the string provided was a valid number or not.

    Notes: Note when passing empty string or '\t\t' and '\n\t' as Number will return 0; Passing true will return 1 and false returns 0.

        Number('34.00') // 34
        Number('-34') // -34
        Number('123e5') // 12300000
        Number('123e-5') // 0.00123
        Number('999999999999') // 999999999999
        Number('9999999999999999') // 10000000000000000 (integer accuracy up to 15 digit)
        Number('0xFF') // 255
        Number('Infinity') // Infinity  
    
        Number('34px') // NaN
        Number('xyz') // NaN
        Number('true') // NaN
        Number('false') // NaN
    
        // cavets
        Number('    ') // 0
        Number('\t\t') // 0
        Number('\n\t') // 0
    

提交回复
热议问题