Basically I was tasked with making a hangman game using ONLY JS and I was using includes( ) as my initial matcher for the users input but have quickly learned that it is A: CASE SENSITIVE (I need it to NOT be) (I could maybe just toUpperCase everything to avoid issues?) B: STOPS after the first match (Obviously not good for words with multiples of a letter) Is there a simple method I could use or am I enslaved to a for loop?
function check(ev) {
const character = ev.key;
// Handle keyboard events
if (
ev.keyCode >= 65 &&
ev.keyCode <= 90 ) {
console.log(ev.keyCode);}
else {
window.alert('Sorry, only letters please! This won\'t cost a life but be careful!');
}
if (selectedWordArr.includes(character)) {
//See if letter was already guessed
if (correctLetters.includes(character)) {
window.alert('Did you forget? You already correctly guessed this letter');
console.log('correct guesses, :' ,correctLetters);
} else {
let correctIndex = selectedWordArr.indexOf(character);
correctLetters.push(character);
maskedArray[correctIndex] = maskedArray[correctIndex].replace('*', character);
console.log('correct guesses, :' ,correctLetters);
CodePudding user response:
Use matchAll()
. To make it case-insensitive, convert the input letter to a regexp with the i
modifier.
let string = "tested";
let letter = "E";
let regexp = new RegExp(letter, "gi"); // case-insensitive regexp
let positions = Array.from(string.matchAll(regexp)).map(m => m.index);
console.log(positions);
CodePudding user response:
forEach is "a simple method".
For example:
const character = ev.key.toLowerCase();
selectedWordArr.forEach((letter, index) => {
if (letter.toLowerCase() === character) {
However, you can't break
out of a forEach
loop, so a for of
loop is often preferred:
for (const [index, letter] of selectedWordArr.entries()) {
if (letter.toLowerCase() === character) {