I am a new to JavaScript. I have tried to use regular expression in ifcondition.
Here is my code:
var location1 = 3;
var location2 = 4;
var location3 = 5;
var guess;
var hits = 0;
var guesses = 0;
var string = "";
var reg = /[0-6]/i;
var isSunk = false;
while (isSunk == false) {
guess = prompt("Ready, aim, fire! (enter a number 0-6): ");
if (guess != reg || guess ==string) {
alert("Please enter a valid cell number!");
} else {
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3) {
hits = hits + 1;
alert("HIT!");
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS!");
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, " + "which means your shooting accuracy was " + (3 / guesses);
alert(stats);`
My problem is in this if (guess != reg || guess ==string) condition. It didn't work as I expected. I would like that function prompt allows only 0,1,2,3,4,5,6 numbers without any words and spaces. But in fact If I enter one of needed number (1 for example) it won't allow to execute further actions. I read a lot through stackoverflow about regular expression in Javascript (Convert the Regular expression, Regular expression, Basic regular expression) and more but I could not find the answer to my problem.
So the question is:
How to set proper regular expression in
ifcondition in JavaScript if it has already declared as variable?
guess != reghere you compare a user string with a regex object; this is not correct, you need toreg.test(guess)You also need to anchor the regex/^[0-6]$/to make it match 1 digit