seanrs97 seanrs97 - 5 months ago 5x
Javascript Question

How can I get my program to swap a string with the key that is pressed down in a specific section of the string?

I'm working on a hangman game in JavaScript and if the user guesses a letter correctly then I need to replace the "-" with the letter that the user has guessed in the corresponding position to where the letter is in the word. I can't seem to be able to replace the string, I can add the string on to the start or end of the "-"'s but when it comes to replacing them, I can't seem to figure out the solution. Any help appreciated. Thanks.

Function that checks if the letter is in the word or not

document.addEventListener("keydown", function textFunction(event)
if (event.keyCode > 64 && event.keyCode < 91)
var guess = event.keyCode;
var a = "a";
var letterGuess = String.fromCharCode(event.keyCode).toLowerCase();
if(sayings[randomSaying].indexOf(letterGuess) >= 0){
var letterLocation = sayings[randomSaying].indexOf(letterGuess) + 1;
progress.innerHTML += letterGuess;
} else {
alert("Please type a letter");

Prints out the dashes

for (var i = 0; i < sayings[randomSaying].length; i++)
progress.innerHTML += "-";


var progress = document.getElementById("dashes");

var sayings = [
"cash on the nail",
"charley horse",
"double cross",
"fit as a fiddle",
"hands down",
"if the cap fits",
"mumbo jumbo",
"see red",
"stone the crows",
"thick and thin",
var randomSaying = Math.floor(Math.random()*sayings.length);


Make a list of it (and drop the +1 because its 0-based now)

if(sayings[randomSaying].indexOf(letterGuess) >= 0){
    var letterLocation = sayings[randomSaying].indexOf(letterGuess);
    var li = progress.innerHTML.split('');
    li[letterLocation] = letterGuess;
    progress.innerHTML = li.join('');

.split('') will split a string into its letters. So for "apple" you get ['a','p','p','l','e'].

Then simply replace the position in the list li[letterLocation] with your letter, and li.join('') the list again.