Reputation: 93
I'm building a hangman game with a database. What my goal is is to store all the guessed letters in my field like "aesdfr". A single string, nothing crazy.
Then I split the letters into an array of guessed letters.
With that in mind, if I have the following
var word = "frog";
var stored_guesses = "frsd"; // hard coded for now
var guessed_letters = stored_guesses.split("");
How do I then go through the guessed letters and present back on the screen "_ " for each letter they didn't guess and show the correct letters for those they did?
I was thinking of looping over each letter in stored_guesses and replacing the original word with hypens for each letter that doesn't exist. But I'm confused.
I'm sure I'm even doing this the word way possible. Is there a better way to store guessed letters and show the encoded word?
Upvotes: 4
Views: 1034
Reputation: 27823
You don't even need to bother with arrays, you can do this with a simple string replace (with a global regexp containing the negated character class of your guessed letters):
var word = "Long word incoming";
var guessed = " aongc";
var regexp = new RegExp('[^' + guessed + ']','g');
var display = word.replace(regexp, '_');
console.log(display);
DEMO: http://jsbin.com/UxixOdA/1/edit
PS: If you want to allow special symbols (other than letters) in your guessed string, you might need to escape them when creating the regexp, or you will have surprises:
// Guesses: a, -, z
var guessed = " a-z"
var regexp = /[^ a-z]/g // matches anything except lowercase letters
Upvotes: 3
Reputation: 4735
ES5 one-liner:
word.split("").map( function(l) { return stored_guesses.indexOf(l) !== -1 ? l : "_" } ) .join("")
If you need older browser support, it can be done with a standard for loop:
var w = word.split("");
var display = "";
for (var i = 0; i< w.length; i++) {
display += stored_guesses.indexOf(w[i]) !== -1 ? w[i] : "_";
}
console.log(display);
Upvotes: 2