views:

3453

answers:

4

does anyone know how can I check variable whether is number or string in javascript

+6  A: 

Use typeof to determine the type of an item.

alert(typeof "Hello World");
alert(typeof 123);
Jonathan Sampson
which says "string" and "number" respectively
Thilo
+1  A: 

Try this,

<script type="text/javascript">
var reInteger = /^\d+$/;

function isInteger (s)
{    
    return reInteger.test(s)
}

if(isInteger("1a11"))
   document.write("Int");
else
  document.write("Not an integer");

</script>
adatapost
+2  A: 

You're looking for isNaN():

<script type="text/javascript">
  alert(isNaN(123));
  alert(isNaN(-1.23));
  alert(isNaN(5-2));
  alert(isNaN(0));
  alert(isNaN("Hello"));
  alert(isNaN("2005/12/12"));
</script>

See JavaScript isNaN() Function at W3schools.com.

Jakob Gade
I find it strange that they would choose the inverse operation for the method name. Seems more intuitive to call isNumber().
Nathan Taylor
Totally agreed. :) JavaScript works in mysterious ways...
Jakob Gade
It isn't actually an inverse operation of 'isNumber'. NaN is a special value of number in javascript. isNaN converts everything supplied to it to number and checks if the result is NaN or not. For strings like "25", you get incorrect result.
Chetan Sastry
I just tested with "25" and it returned false - like I would expect.
Jakob Gade
But "25" is a string, not a number.
Matthew Crumley
Ahh, now I get it. :)
Jakob Gade
NaN is a special value in the IEEE 754 Standard for Binary Floating-Point Arithmetic, not just a JavaScript thing. (Well, to be precise: *"the 9007199254740990 (that is, (2^53)-2) distinct “Not-a-Number” values of the IEEE Standard are represented in ECMAScript as a single special NaN value."*)
NickFitz
+2  A: 

Best way to do that it's use isNaN + type casting:

function isNumber (o) {
  return ! isNaN (o-0);
}

isNumber ('123'); // true  
isNumber (5); // true  
isNumber ('q345'); // false
Tumtu
This looks like a good solution if you want to count strings that parse as valid numbers.
Trevor Burnham