.includes() Is always returning true - javascript

I am trying to make a Wordle type game, I have started on the basics where it is just using the console to tell me weather the letters are correct or not. In the function check letter the first if statement works flawlessly but on the second one when it is checking weather or not the guess and the word both have the same letter just not in the correct spot. But even when the letter is not even in both of the variable it will console "wrong spot" instead of "wrong letter".
const word = "Lucas";
let guessed = prompt("Please Guess The Word");
checkLength()
function checkLength() {
if (word.length == guessed.length) {
console.log("It Worked")
checkLetter(0)
checkLetter(1)
checkLetter(2)
checkLetter(3)
checkLetter(4)
} else {
console.log("It Failed")
guessed = prompt("Please Use 5 Letters");
}
}
function checkLetter(letterPos) {
if (word.charAt(letterPos) == guessed.charAt(letterPos)) {
console.log("Same Letter! " + letterPos)
} else {
let letterW = word.charAt(letterPos)
let letterG = guessed.charAt(letterPos)
if (word.includes(letterW) == guessed.includes(letterG)) {
console.log("Wrong Spot " + letterPos)
} else {
console.log("Wrong Letter " + letterPos)
}
}
}

The problem is that includes returns true or false, not the index, so when both world and guessed don't include the letter, false == false would return true:
if (letterG !== letterw && word.includes(letterW))
The above condition should work.

First, we should clean up the variables. Then, all that needs fixing is the second if statement. We want to check if letterG exists in word, if not, then it's the wrong letter.
function checkLetter(letterPos) {
let letterW = word.charAt(letterPos);
let letterG = guessed.charAt(letterPos);
if (letterW == letterG) {
console.log("Same Letter! " + letterPos)
} else if (word.includes(letterG)) {
console.log("Wrong Spot " + letterPos)
} else {
console.log("Wrong Letter " + letterPos)
}
}

Related

I'm trying to make a question prompt, but It wont load in the prompt due to syntax error

I'm trying to make this put up an alert when answering the first prompt, can anyone help?
var answer = "Griffin"
var answer2 = "griffin"
if(prompt("What's your name?"))
{
if(answer === ("Griffin"))
{
var callback = function() {
alert("Oh hi! " + answer)
}
}
} else {
if(answer2 === ("griffin"))
{
setTimeout(callback, 1000);
} else {
alert("Then whats your name if it's not Griffin?")
}
}
remove the semicolon in the if-statement and use comparator operator(==) instead of assign operator(=) in if-statment
here is the updated code
var answer = 'Griffin';
var answer2 = 'griffin';
if (prompt("What's your name?")) {
if ((answer == 'Griffin')) {
var callback = function () {
alert('Oh hi! ' + answer);
};
}
} else {
if ((answer2 == 'griffin')) {
setTimeout(callback, 1000);
} else {
alert("Then whats your name if it's not Griffin?");
}
}
Replace the single equals in the if blocks with a triple equal. In this case, you assign the value instead of checking it and also remove the semicolon in the first if, before the executing block;
Later edit:
Your question is not that clear, so I try to update the answer somehow accordingly.
var userAnswer = prompt("What's your name?"); // keep a reference to what user types in
switch (userAnswer) {
case 'Griffin':
// do something, alert, etc
alert("Oh hi! " + userAnswer);
break;
case 'griffin':
// do something else
alert("Oh hi! griffin");
break;
default:
// if none of the above cases are matched
alert("Then what's your name if it's not Griffin?");
break;
}
var answer = "Griffin"
var answer2 = "griffin"
var verify = prompt("What's your name?")
if (verify == answer) {
callback()
}
else if
(verify == answer2) {
alert("Oh hi! " + answer2)
}
else {
alert("Then whats your name if it's not Griffin?")
}
function callback(){
alert("Oh hi! " + answer)
}
var answer = "Griffin"
var answer2 = "griffin"
//here we need variable ,it will hold the prompt input..
var promptInput = prompt("what is your name?")
if (promptInput == "Griffin") {
var callback = function call() {
alert("Oh hi! " + answer)
}
callback();//if it is "Griffin" it is going to call the function which is callback()
}
else if (promptInput == "griffin") {
setTimeout(callback, 1000);
}
else {
alert("Then whats your name if it's not Griffin?")
}

How to tell if not number or letter

I have the following bit of code which is working, my question is if the user enters something that is not a letter or number how would I go about doing this ?
E.g they enter the letter "?" I want the console to now say " ? is not a letter or number" please see my below code to see what I currently have.
let upperLower = prompt("please enter either a uppercase letter, lowercase letter or a number");
if (!isNaN(parseInt(upperLower))){
console.log(upperLower + " is a number");
}
else if (upperLower == upperLower.toLowerCase()) {
console.log(upperLower + " character is lowercase");
}
else if (upperLower == upperLower.toUpperCase()) {
console.log(upperLower + " character is uppercase");
}`
function isNotAlphanumeric(str) {
return !(str.length === 1 && (/[a-z\d]/i).test(str));
}
using How to check if character is a letter in Javascript?
Implementation:
let upperLower = prompt("please enter either a uppercase letter, lowercase letter or a number");
if( (upperLower.toUpperCase() == upperLower.toLowerCase() || upperLower.codePointAt(0) > 127) && isNaN(parseInt(upperLower))) {
console.log(upperLower + " is not a letter or number");
}
else if (!isNaN(parseInt(upperLower))){
console.log(upperLower + " is a number");
}
else if (upperLower == upperLower.toLowerCase()) {
console.log(upperLower + " character is lowercase");
}
else if (upperLower == upperLower.toUpperCase()) {
console.log(upperLower + " character is uppercase");
}
This problem can be solved using a regular expression. Tested on Regex101.
var foo = prompt("please enter either a character or integer");
// if word character or digit => true, else => false
const bar = new RegExp(/[\da-z]+/, "i");
// is any digit => true, else => false
const numberRE = /\d+/;
if (bar.test(foo)){
// if a number, log it's a number, else it's a string
if (numberRE.test(foo)) {
console.log("You entered a number");
} else {
console.log("You entered a letter");
}
// if input isn't a digit or word character, log this
} else {
console.log("Enter a character or integer!");
}
Use RegEx:
if (/^[0-9]+(?:\.[0-9]+)?$/.test(upperLower)) { // 123 or 123.456
console.log(upperLower, "is a number")
}
if (/^[0-9]+$/.test(upperLower)) { // only 123
console.log(upperLower, "is a number")
}
if (/^[a-z]+$/.test(upperLower)) {
console.log(upperLower, "is a lowercase")
}
if (/^[A-Z]+$/.test(upperLower)) {
console.log(upperLower, "is a uppercase")
}
You can test any regex in regex101.

Javascript: Alert message after loop ends

This is a simple login excercise for school. It is meant to give you 3 attempts to log in. I would like to make it so after the loop stops (the three attempts were used), it alerts the user that he has no remaining attempts and his account will be blocked.
Something like:
alert("You don't have any attempts left. Your account is now blocked);
Here is the loop I made:
var tries;
for (tries = 2; tries !== -1; tries--) {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
alert("Welcome.");
break;
} else {
alert("Incorrect username and/or password. You have " + tries + " attempt(s) left.");
}
}
Thanks in advance.
You where very close. I think this is what you want.
var tries;
for (tries = 2; tries >= 0; tries--) {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
alert("Welcome.");
break;
} else if (tries == 0) {
alert("You don't have any attempts left. Your account is now blocked");
} else {
alert("Incorrect username and/or password. You have " + tries + " attempt(s) left.");
}
}
You can achieve this recursively. Just decrease the number of Tries everytime wrong username or password is entered.
var TRIES = 3;
function ask() {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
return alert("Welcome.");
}
if (TRIES > 0) {
alert("Incorrect username and/or password. You have " + TRIES + " attempt(s) left.");
TRIES -= 1;
ask()
} else {
alert("You don't have any attempts left. Your account is now blocked");
}
}
ask()
var tries;
for (tries = 0; tries < 3; tries++) {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
alert("Welcome.");
break;
} else {
alert("Incorrect username and/or password. You have " + tries + " attempt(s) left.");
}
if(tries == 2)
{
alert("You don't have any attempts left. Your account is now blocked);
}
}
Perhaps you could achieve this by doing the following:
for (var attemptsRemaining = 3; attemptsRemaining > 0; attemptsRemaining--) {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
alert("Welcome.");
break;
} else if(attemptsRemaining <= 1) {
alert("To many failed attempts. Your account is now blocked.");
}
else {
alert("Incorrect username and/or password. You have " + (attemptsRemaining - 1) + " attempt(s) left.");
}
}
}
The idea here is to add an additional check to see if the number of attemptsRemaining has reached one (or less, for robustness) at which point all attempts are expired. In this case, you display a popup to alert notifying the user that their account is now blocked.
Hope that helps!

If user "cancels" prompt box then

I have tried adding a Do/While loop, then I tried a If statement but I can't seem to get this to work.
I am trying to determine if the user hasn't made three guesses, and hits cancel on the userGuess prompt .. it would then return a alert("You are a chicken");
//declare variables
var sportsArray = new Array("Football", "Basketball", "Rollerblading", "Hiking", "Biking", "Swimming");
var name = "";
var score = 0;
var loops = 0;
// prompts for user name, checks for input.
do {
name = prompt("Enter your first name", "");
}
while (name == "");
for (loops = 1;loops <=3; loops++) {
var sGuess = prompt("Enter a sport guess", "");
// uses substrings to ultimately capitalize the 1st letter, and make everything after it lowerCase.
var sFirstPart = sGuess.substr(0, 1);
var sFirstCap = sFirstPart.toUpperCase();
var sSecondPart = sGuess.substring(1, sGuess.length);
var sSecondLow = sSecondPart.toLowerCase();
// concats the two parts into one string
var usableGuess = sFirstCap + sSecondLow;
// if user hits cancel on the sGuess prompt
if (sGuess == "") {
alert("You are a chicken");
}
// checks if usableGuess is contained in the arry or not.
if (sportsArray.indexOf(usableGuess) === -1) {
document.write("Sorry! Try again.<br />");
score = score -5;
}
else {
document.write("You are good, try again.<br />");
score = score + 5;
}
}
//depending on the user score, prompts one of three messages.
if (score < 0) {
document.write(name + ", you do not demonstrate ESP tendencies at this time.<br />");
} else if (score < 15) {
document.write(name + ", you are not bad.<br />");
} else {
document.write("<br/>" + name + ", you are a mind reader!<br />");
}
The prompt return s a null value where clicked on cancel, so your substring() method fails with an error(Uncaught TypeError: Cannot read property 'substr' of null).
You need to check it as soon as the prompt is called, then continue like
var sGuess = prompt("Enter a sport guess", "");
if (sGuess == "") {
alert("You are a chicken");
continue;
}
Update sGuess checking from:
if (sGuess == "") {
alert("You are a chicken");
}
to next one:
if (sGuess == null) {
alert("You are a chicken");
}
If user click cancel sGuess would be equal to null, to verify third user tries was ended with cancel pressing add checking for loops counter value (sGuess == null && loops == 3).
Just check the result to see if there was a value supplied:
name = prompt("Enter your first name", "");
// If no name value was received:
if(!name){
alert("Chicken!");
}
"prompt" is returning null if the user hits cancel. In this case all your substr and subsequent code will fail.
var sGuess = prompt("Enter a sport guess", "");
if(sGuess !== null) {
// uses substrings to ultimately capitalize the 1st letter, and make everything after it lowerCase.
var sFirstPart = sGuess.substr(0, 1);
var sFirstCap = sFirstPart.toUpperCase();
var sSecondPart = sGuess.substring(1, sGuess.length);
var sSecondLow = sSecondPart.toLowerCase();
// concats the two parts into one string
var usableGuess = sFirstCap + sSecondLow;
} else {
// if user hits cancel on the sGuess prompt
alert("You are a chicken");
}
...
I ended up going with the following and it does the job, in this particular case.
// if user hits cancel on the sGuess prompt
if (!sGuess && loops < 4) {
alert("You are a chicken");
}

javascript if elseif else not working

Help! The if/elseif/else code block won't work! When the code reaches prompt "what will you do?" no matter what you type, you get all the alerts. It should come up blank when you type a command that is not in the if blocks, and give you an alert if you did type R, L or M. Typing F should give you no alert.
while (Room = 1) {
var Choice = prompt ("What will you do?");
if (Turn = "Start");
{
if (Choice = "F");
{
Turn = "1";
}
else if (Choice = "R");
{
alert ("You cannot do that...");
}
else if (Choice = "L");
{
alert ("You cannot do that...");
}
else if (Choice = "M");
{
alert (" 1"+'\n'+" 1" + '\n' + "221" + '\n' + " X");
}
else
{
alert ("You cannot do that...")
}
}
Use == instead of =. A single equals is a variable assignment and evaluates to the result of the assignment. == is used for equality test.
Remove ; from your if and else if statement.
; represents end of statement
Also you can't use = as comparison operation, instead == or ===(strict comparison) as #Andy mentioned.
while (Room == 1) { // Actually your code fails at the beginning itself.
However I would suggest you to use switch for your case.
If you write "=" single equal to means assignment of value to that variable.
So, You should change the "=" Single equalto to "==" Double equalto for conditional purpose.
And If else has no end ";" Semi-Colon required in Javascript. removed it.
I have updated the following please try it.
while (Room == 1) {
var Choice = prompt ("What will you do?");
if (Turn == "Start")
{
if (Choice == "F")
{
Turn == "1";
}
else if (Choice == "R")
{
alert ("You cannot do that...");
}
else if (Choice == "L")
{
alert ("You cannot do that...");
}
else if (Choice == "M")
{
alert (" 1"+'\n'+" 1" + '\n' + "221" + '\n' + " X");
}
else
{
alert ("You cannot do that...");
}
}
}
You have a semicolon after all your if-elseif-statements. So regardless of what the boolean is inside the if, the if block is empty. Just remove semicolons and you're good to go.
With this:
if(1 == 1);
{
alert('Nope');
}
the block after if-statement is always executed because of the semicolon ending the if.
if(1 == 1)
{
alert('Yup');
}
Works.
Java scrip don't consider single '=' it works with '=='
try
if (Turn == "Start");
Instead of
if (Turn = "Start");
Remove semicolons ; at the end of the if and else if loops
and also compare string by using ==, not =
Replace your code with this one
while (Room = 1) { //here Room is int variable
var Choice = prompt ("What will you do?");
if (Turn == "Start")
{
if (Choice =="F")
{
Turn = "1";
}
else if (Choice == "R")
{
alert ("You cannot do that...");
}
else if (Choice == "L")
{
alert ("You cannot do that...");
}
else if (Choice == "M")
{
alert ("1" + '\n' + "1" + '\n' + "221" + '\n' + "X");
}
else
{
alert ("You cannot do that...")
}
}
Also, besides using strict comparison I would strongly suggest writing left curly brace just after if(...) not in the new line:
Like:
if(...){
Instead of:
if(...)
{
Reason for that is JavaScript's built-in semi-colon insertion, so sometimes it can produce silent errors or unexpected behavior. In some other programming languages it doesn't matter, but in JavaScript it does.

Categories