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

前端 未结 30 3410
-上瘾入骨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条回答
  •  遥遥无期
    2020-11-22 02:31

    Quote:

    isNaN(num) // returns true if the variable does NOT contain a valid number

    is not entirely true if you need to check for leading/trailing spaces - for example when a certain quantity of digits is required, and you need to get, say, '1111' and not ' 111' or '111 ' for perhaps a PIN input.

    Better to use:

    var num = /^\d+$/.test(num)
    

提交回复
热议问题