Javascript parsing an integer from a string

What I want to do is determine if the string is numeric. I would like to know what people think of the two solutions that I am trying to solve between (OR, if there is a better solution that I have not found yet). The parseInt function is not suitable because it will return an integer value for a parameter of type "40 years". Two solutions that I decide between:

Use Integer.valueOf () with try catch

function isNumeric(quantity)
{
    var isNumeric = true
    try
    {
        Integer.valueOf(quantity)
    }
    catch(err)
    {
        isNumeric = false
    }
    return isNumeric
}

Or check each character separately

function IsNumeric(quantity)
{
    var validChars = "0123456789";
    var isNumber = true;
    var nextChar;

    for (i = 0; i < quantity.length && isNumber == true; i++) 
    { 
        nexChar = quantity.charAt(i); 
        if (validChars.indexOf(nextChar) == -1) 
        {
            isNumber = false;
        }
    }
    return IsNumber;
}

I would have thought that there would be a simpler solution than both of them. Did I miss something?

NOTE. I use jQuery aswel, so if there is a jQuery solution that would be enough

+3
source share
7 answers

- , , , ( ..), Number, -.

, !isNaN(true) == true .

30 + unit test, , , :

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
+11

isNaN(obj)?

function IsNumeric (value) {
    return (!((isNaN(value)) || (value.length == 0)));
}
+7

?

function IsNumeric(string) { 
    return string.match(/^\d+$/) !== null;
}

( , )

+4

function isNumericString(s)
{
   return !!s && !isNaN(+s);
}

+ - . , .

+1

I suppose you could use a regex to validate input, but I honestly don't see what is wrong with the first.

0
source

If you are only checking strings, why not let any string use this method?

String.prototype.isNumeric= function(){
 return parseFloat(this)== this;
}
0
source

Here is my solution with parseInt that will work:

var str = "40 years old";
var isNumeric = parseInt(str) == str ? true : false;
0
source

Source: https://habr.com/ru/post/1720236/


All Articles