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
2009-08-20 02:25:14
which says "string" and "number" respectively
Thilo
2010-09-29 02:47:11
+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
2009-08-20 02:38:12
+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
2009-08-20 02:50:20
I find it strange that they would choose the inverse operation for the method name. Seems more intuitive to call isNumber().
Nathan Taylor
2009-08-20 02:54:52
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
2009-08-20 03:14:05
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
2009-08-20 09:42:13
+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
2009-09-14 14:40:20
This looks like a good solution if you want to count strings that parse as valid numbers.
Trevor Burnham
2010-07-16 11:42:48