I’m trying to create a game in which, Starting of the game I have to ask the user for ‘How many times he wants to play‘ and the user input must be an integer.
So I write the code I shared below. But it doesn’t work as I expected.
If anyone can help me to figure out what I did wrong it will be helpful to me.
Thanks in advance.
let playCount = 0;
let regxNum = /^[0-9]+$/g; //Regular Expression to select all numbers between 0-9.
let checkPlayCount = 0;
let askPlayCount = () => { //Function to get game play count.
checkPlayCount = 0;
playCount = Number(prompt("How many times you want to play: ")); //Gets play count and convert into number;
checkPlayCount = Array.from(String(playCount), Number); //Converts number into array
}
askPlayCount();
//Code for validating input : must be number.
for(let i = 0; i < checkPlayCount.length; i++){
if(checkPlayCount[i] != regxNum){
console.log("Please enter valid input");
askPlayCount();
}
}
2
Answers
The problem is you convert the number into the array, while you simply can do this by directly checking the input against regex. Here is my version of the problem
You could just convert the input to a number and check if it
Number.isInteger()