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

前端 未结 30 3342
-上瘾入骨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:39

    This is built on some of the previous answers and comments. The following covers all the edge cases and fairly concise as well:

    const isNumRegEx = /^-?(\d*\.)?\d+$/;
    
    function isNumeric(n, allowScientificNotation = false) {
        return allowScientificNotation ? 
                    !Number.isNaN(parseFloat(n)) && Number.isFinite(n) :
                    isNumRegEx.test(n);
    }
    

提交回复
热议问题