1

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

User One
  • 55
  • 4
  • 2
    I guess you could `eval` the input, but… anything the user inputs is by definition a string. A string *may* be able to be interpreted in some other type, e.g. `'1'` can be cast to `1`, `'true'` can be interpreted as `true`. But, how to distinguish when the user meant to type the *string* `'true'`, not a boolean? You could require *JSON* as input and `JSON.parse()` it, `'true'` means the boolean `true`, and `'"true"'` means the string `'true'`… – deceze Jul 17 '20 at 09:11
  • Does this answer your question? [How to convert instance of any type to string?](https://stackoverflow.com/questions/869773/how-to-convert-instance-of-any-type-to-string) –  Jul 17 '20 at 09:32

2 Answers2

1

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"
}
not-a-robot
  • 321
  • 1
  • 14
1

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.

mw509
  • 1,957
  • 1
  • 19
  • 25