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

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

    My solution:

    // returns true for positive ints; 
    // no scientific notation, hexadecimals or floating point dots
    
    var isPositiveInt = function(str) { 
       var result = true, chr;
       for (var i = 0, n = str.length; i < n; i++) {
           chr = str.charAt(i);
           if ((chr < "0" || chr > "9") && chr != ",") { //not digit or thousands separator
             result = false;
             break;
           };
           if (i == 0 && (chr == "0" || chr == ",")) {  //should not start with 0 or ,
             result = false;
             break;
           };
       };
       return result;
     };
    

    You can add additional conditions inside the loop, to fit you particular needs.

提交回复
热议问题