I am receiving var value by:
var val=document.getElementById('ctl00_ContentPlaceHoldermain_TextBox1').value;
In my code I am checking type of each character using 'typeof'. But always it is returning string only. How to identify the number?
I am receiving var value by:
var val=document.getElementById('ctl00_ContentPlaceHoldermain_TextBox1').value;
In my code I am checking type of each character using 'typeof'. But always it is returning string only. How to identify the number?
You can use parseInt
or parseFloat
. If parseInt(str)
returns NaN
so your string is not a number.
You can use only for strings that contains only digits: parseInt('123')
. If it possible that your string can contains letters too so you can get some problems:
parseInt('123') // -> 123
parseInt('123asd') // '123asd' is not a number but parseInt returns 123
So more simple way is to use jQuery
's isNumeric
function or implement it by yourself
You can see more about it from the link in the @Rahat's comment.
Also you can see at this blog post
I agree with alternative answer but I think parseInt
and parseFloat
should be used for parsing because they are meant for it. isNaN
function can give you numeric checking functionality.
function isNumber(val) {
if(val == "") {
return false;
}
return !isNaN(val);
}
As per comment, if you want to select number from array then you can simply create loop and call it inside. e.g
var vals = ['dsds','2','','4'];
for (var i = 0; i<vals.length; i++) {
if(isNumber(vals[i]) {
// it's number
}
else {
// it's not number;
}
}