I've found a large number of posts discussing find/replace methods for strings in arrays, however they all seem to rely on a 'static string' input for the replacement
ie:
var str = "Mr Blue has a blue house and a blue car";
var res = str.replace(/blue/g, "red");
I need to find and replace checking against an input event
var whichKey = (String.fromCharCode(event.keyCode));
but also dynamically find and replace the characters that match in a different string.
so to be clear:
I am making a game of 'hangman'
user presses 'W' (for instance) as a 'guess':
secretPuzzleSolution = ['s', 'o', 'l', 'u', 't', 'i', 'o', 'n']
puzzleUserSees = ['_', '_', '_', '_', '_', '_', '_', '_']
W is not in the puzzle so they will lose a 'try' if they press 'S' the code would check secretPuzzleSolution[] for 's' and replace all the '_' in puzzleUserSees[] to 's' at the correct places and returns a new puzzleUserSees = ['S', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ', ' _ ',] as a result.
The code successfully finds the keypress in secretPuzzleSolution[] but I cannot so far get it to
copy the position from secretPuzzleSolution[] so that the puzzleUserSees[] element is changed at the correct position
replace ALL instances of the keypress, not just the first one (if there's two elements of 's' in secretPuzzleSolution[], change both at the correct positions in puzzleUserSees[]
what I've got so far, it does partially do the job, but as you can see is clearly broken in a number of ways. Any ideas?
Here's the section I'm working with:
document.onkeydown = function(e) {
var whichKey = (String.fromCharCode(event.keyCode));
var keyPress = whichKey.toLocaleLowerCase();
var found = secretPuzzleSolution.find(function(element) {
var isMatch = secretPuzzleSolution.indexOf(element);
if (typeof(element) !== 'undefined') {
puzzleUserSees.splice((isMatch), (isMatch), element);
remainingMystery--;
} else {
guessList.push(keyPress);
triesLeft--;
}
return element === keyPress;
});
if (remainingMystery <= 0) {
document.getElementById('game-display-area').innerHTML = ('YOU WIN!')
};
console.log('These guesses were correct: ' + found);
};
The last thing I'll add is that I'm in school so I'm sure there's a fancy way to do this or with jQuery but there should be a simple way with just JS as that's all I'm supposed to know so far :)
something else I tried:
var test_array = (secretPuzzleSolution.indexOf(keyPress) > -1);
if (test_array === true) {
console.log(keyPress + ' was found in the puzzle');
for (i = 0; i < puzzleUserSees.length; i++) {
if (keyPress === puzzleUserSees[i]) {
puzzleUserSees.splice([i], keyPress)
}
}
} else {
triesLeft--;
guessList.push(keyPress);
console.log(keyPress + ' was NOT found');
}
Thanks!