Deniss Muntjans
Deniss Muntjans

Reputation: 379

Define which type is inserted String or int

How to define which type of variable is typed in text field? I wish to type something inside text field when you press on Search button depending on type it should show you different results from database!

if(numbers 0-9){
   //do something
}  
else if (letters A-Z){
   //do something else
}

How to do that in javascript?

Upvotes: 0

Views: 52

Answers (3)

Ricky Stam
Ricky Stam

Reputation: 2126

You can try to convert a string into integer by doing:

var a = "3";
var b = +a; // this will try to convert a variable into integer if it can't it will be NaN

you can check if

Boolean(+a) is true then a is Number else it's not a number

Upvotes: 0

chridam
chridam

Reputation: 103435

You could try the method toType defined by Angus Croll in this blog post:

var toType = function(obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}

Implementation:

toType({a: 4}); //"object"
toType([1, 2, 3]); //"array"
(function() {console.log(toType(arguments))})(); //arguments
toType(new ReferenceError); //"error"
toType(new Date); //"date"
toType(/a-z/); //"regexp"
toType(Math); //"math"
toType(JSON); //"json"
toType(new Number(4)); //"number"
toType(new String("abc")); //"string"
toType(new Boolean(true)); //"boolean"

Upvotes: 0

Lucky Lefty
Lucky Lefty

Reputation: 347

most go with

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

Upvotes: 3

Related Questions