Check if string contains only digits

patad picture patad · Nov 22, 2009 · Viewed 377.9k times · Source

I want to check if a string contains only digits. I used this:

var isANumber = isNaN(theValue) === false;

if (isANumber){
    ..
}

But realized that it also allows + and -. Basically, I wanna make sure an input contains ONLY digits and no other characters. Since +100 and -5 are both numbers, isNaN() is not the right way to go. Perhaps a regexp is what I need? Any tips?

Answer

Scott Evernden picture Scott Evernden · Nov 22, 2009

how about

let isnum = /^\d+$/.test(val);