0

JS turns all prompt input into a string. I'd like to test if it is an actual number and if yes, turn the type into a number. What's the best way to do it? If I use Number(target), it turns any string into a number type too.

    var res = prompt('How long'); //input: "ABC" 
    typeof Number(res)
    >> "number"
somniumm
  • 115
  • 1
  • 10

3 Answers3

0

In this case you can take help of regex

let isNum = /^\d+$/.test(res);

the result in isNum will either be true or false depending on your input. if the result is true then you can convert it to number

if (isNum)
  let num = parseInt(res)
rajabraza
  • 333
  • 3
  • 11
0

// let res = +(prompt('How long') // + convert to number
if(res = +(prompt('How long'))){
  console.log('Its number : ', res);
}else{
  console.log("Its not a number");
}
navnath
  • 3,548
  • 1
  • 11
  • 19
0

There are different approaches to reach that but one of the best practices is:

First, get the input:

let result = prompt('How long');

Convert input to number:

let resultNumber = Number(result);

Now, time to validate our resultNumber:

if(!Number.isNaN(resultNumber)) {
  // It's a actual number  
} else {
  // It's not a number
}

Note 1: converting strings into numbers does not always produce numbers, NaN is the result of those converting, let's take an example

Number('false') // --> NaN

Note 2: If the number is an actual number so it is converted to a number type but in the case of NaN the Number.isNaN() will check it.

nima
  • 7,796
  • 12
  • 36
  • 53