'Javascript - Giving alert for string input but number

Hi recently I was writing a code which basically askes users to input a cost for any item. The item name or price are not important so far. How the system works is that a prompt pops up and asks what is the cost of the item, and when you enter a cost, it asks you again (while loop). When total cost reaches $36, while loop ends and an alert screen pops up saying your shipping is free since it is over $35.

My problem is when I enter string value as a user input it takes the value into cost array and since it goes as Nan value, my cost calculation never end even though it passes $36.

How can I eliminate any string input and do not push it into the array?

Here is my code:

while (complete === false) {
var costValue = prompt('Enter the cost of the item?');

//If user click cancel
if (costValue === null) {
alert('Process canceled');
complete = true;} 

//AT THIS LINE HOW CAN I ELIMINATE STRING VALUES
//convert input to a number
userInput = parseInt(costValue);
/push the value into the array
myCost.push(userInput);


Solution 1:[1]

Leading special character will give you NAN and if you use a special character after the Int value then the parseInt will give you the correct result. You can also use regex to remove all the special characters.

userInput.replace(/[^\w\s]/gi, '')

You can read about parseInt from here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Solution 2:[2]

After you parse your user input into an integer (i.e. using parseInt method), then have an if statement that checks whether the parsed values is not NaN. If so, then only push the parsed value into your array.

// TRY parse user input into an integer
userInput = parseInt(costValue);

// only push into your array when it is not `NaN`
if (userInput !== 'NaN') {
// push the value into the array
myCost.push(userInput);
}

Solution 3:[3]

Try this code, it should work

var userInput;
var totalInput=0;
var complete = false;
var costValue;
var numPattern = /^\d+$/;

while (!complete) {
    costValue = prompt('Enter the cost of the item?');

    //If user click cancel
    if (costValue === null) 
    {
        alert('Process canceled');
        complete = true;
    } 

    //convert input to a number if it matches regular expression
    if (costValue.match(numPattern)){
        userInput = parseInt(costValue);

        totalInput+=userInput;
    
        if (totalInput>35) {
          complete=true;
          alert("Cost is $" + totalInput + ". Shipping is free over $35");
        }
    }
}

Solution 4:[4]

On the other hand, if you want to go another route, you can check for NaN using this function isNaN(userInput) and exclude it from your calculations

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mahadi Hasan
Solution 2 Nidhi
Solution 3 Frida
Solution 4 Frida