User One
User One

Reputation: 55

Finding variable types from a string

Pardon if this question has already been answered however I'm struggling to find the any answers to it.

I'm looking to see if I can convert variable types to a string in the code below.

input = prompt('Type something please', 'your input here')
alert(input + ' is a ' + typeof input)

i.e. if the user were to type 1 typeof would return number, or if the user were to enter true it would return a boolean

Upvotes: 1

Views: 87

Answers (2)

mw509
mw509

Reputation: 2093

Generally, all inputs per your example will return a string careless of what they entered or intended to enter. We could however build a few logics to check if what they entered is; Strings (Alphabets only) or an integer (numbers only) or any other ones per a few other logics you could base your checks on.

One of the quickest ways to check if an input contains a number or not;

isNaN(input)         // this returns true if the variable does NOT contain a valid number

eg.
isNaN(123)         // false
isNaN('123')       // false
isNaN('1e10000')   // false (This translates to Infinity, which is a number)
isNaN('foo')       // true
isNaN('10px')      // true

you could try regex (which is not always ideal but works)

var input = "123";

if(num.match(/^-{0,1}\d+$/)){
  //return true if positive or negative
}else if(num.match(/^\d+\.\d+$/)){
  //return true if float
}else{
  // return false neither worked
}

You could also use the (typeof input) but this will be more convenient if your user is going to enter an expected set of entries

var input = true;
alert(typeof input);
// This eg will return bolean

Let me know if this helps.

Upvotes: 1

not-a-robot
not-a-robot

Reputation: 321

You can run the input through a series of parseInt, parseFloat and parseBool functions.

Whenever you get a valid result, return it.

Something similar to:

if (parseInt(input) != NaN) {
  return "int"
}
if (parseFloat(input) != NaN) {
  return "float"
}

Upvotes: 1

Related Questions