views:

595

answers:

5

Hello

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 the input contains ONLY digits and no other letters. Since +100 and -5 are both numbers, isNaN, is not the right way to go. Perhaps a regexp is what I need? Any tips?

+6  A: 

how about

var isnum = /^\d+$/.test(val);
Scott Evernden
+1  A: 

Well, you can use the following regex:

^\d+$
Joey
+2  A: 
string.match(/^[0-9]+$/) != null;
Jason S
+3  A: 
var isNumber =  /^\d+$/.test(theValue);
Øystein Riiser Gundersen
+1  A: 
String.prototype.isNumber = function(){return /^\d+$/.test(this);}
console.log("123123".isNumber()); // outputs true
console.log("+12".isNumber()); // outputs false
balupton