-1

I'm struggling too much for this task. I need to make it; check to see if the word that i had written matches up to the word that is in the array. (single letter). if it does, it should replace the underscores with the characters that are in that word! How should I do it?

this is for a game like hangman btw This is my code:

<script>

var words = ["kite", "boom", "zoom", "tall", "table", "biscuit", "pie"];

window.addEventListener("load", function() {

  var submitbtn = document.getElementById("button")
  var userInput = document.getElementById("userInput");

  submitbtn.addEventListener("click", checkAnswer, false);



  var wordElt = document.getElementById("word");
  var word = words[Math.floor(Math.random() * words.length)];

  for ( var i=0; i < word.length; i++ ) {

        //display += "_ ";
        wordElt.textContent += "  _  ";
  }

  var split = word.split("");
  console.log(word)

});

function check(){

}

Llewellyn Collins
  • 2,243
  • 2
  • 23
  • 37
bob mike
  • 1
  • 1
  • 1
    Have a look at how to write a regular expression, and how to use the methods of regular expressions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions – 2540625 Aug 12 '14 at 07:53
  • What is "see if the word that i had written matches up to the word that is in the array. (single letter)." supposed to mean. Are you checking to see if the a word or a letter is in the array? Then replace the characters with what? – James Aug 12 '14 at 07:54
  • `function check(){ ) }` looks very strange to me... Please indent your code properly. – Reeno Aug 12 '14 at 07:55

1 Answers1

0

You can't replace a letter in string, because javascript strings are immutable - see this answer from which you can borrow

String.prototype.replaceAt=function(index, character) {
  return this.substr(0, index) + character + this.substr(index+character.length);
}

Then (if you code the Hangman game) you can replace the occurences using string indexOf method:

var theWord = "H___o";
var theLetter = "l";
var keyWord = "Hello";

while(true) {
  var i = keyWord.indexOf(theLetter);
  if(i==-1) break;
  theWord = theWord.replaceAt(i,theLetter);
  keyWord = keyWord.replaceAt(i,"_");
}

// theWord = H_llo
// keyWord = He__o
Community
  • 1
  • 1
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
  • ima fail this task :( – bob mike Aug 12 '14 at 09:18
  • chin up - the code above replaces one particular letter (l) for the underscores in `theWord` in positions where it occurs in `keyWord`. Now put it together with your code: `theLetter` is what you read from `userInput`, replace your for cycle for my while cycle, add `wordElt.innerHTML = theWord` and the day is saved. – Jan Turoň Aug 12 '14 at 09:45
  • man, im so sad, i have no idea what im doing. do you think you could help me through teamviewer or something? id be so greatful :( – bob mike Aug 12 '14 at 09:59
  • That is not the purpose of this site. Write me an e-mail. – Jan Turoň Aug 13 '14 at 09:29