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

2
  • 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' Commented Jul 17, 2020 at 9:11
  • Does this answer your question? How to convert instance of any type to string? Commented Jul 17, 2020 at 9:32

2 Answers 2

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"
}
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Thanks! I've been able to implement this answer too :)
you might want to vote and clap for us. It makes us feel good if you know what I mean. :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.