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

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

    If you're just trying to check if a string is a whole number (no decimal places), regex is a good way to go. Other methods such as isNaN are too complicated for something so simple.

        function isNumeric(value) {
            return /^-?\d+$/.test(value);
        }
        
        console.log(isNumeric('abcd'));         // false
        console.log(isNumeric('123a'));         // false
        console.log(isNumeric('1'));            // true
        console.log(isNumeric('1234567890'));   // true
        console.log(isNumeric('-23'));          // true
        console.log(isNumeric(1234));           // true
        console.log(isNumeric('123.4'));        // false
        console.log(isNumeric(''));             // false
        console.log(isNumeric(undefined));      // false
        console.log(isNumeric(null));           // false
    

    To only allow positive whole numbers use this:

        function isNumeric(value) {
            return /^\d+$/.test(value);
        }
    
        console.log(isNumeric('123'));          // true
        console.log(isNumeric('-23'));          // false
    

提交回复
热议问题