0

I am creating a Hangman game and want to check whether a letter is in a string and if it is change that part of the word into the letter. My HTML:

<div id="word">

  <span id="letter_0"></span><span id="letter_1"></span><span id="letter_2"></span><span id="letter_3"></span><span id="letter_4"></span><span id="letter_5"></span><span id="letter_6"></span><span id="letter_7"></span><span id="letter_8"></span><span id="letter_9"></span>

</div>

Here is my javascript for the letter "a".

    function A(event) {

  for (var letter = 0; letter <= randomWord.length; letter++) {

    if (randomWord[letter] = "a") {

      document.getElementById("letter_" + letter).innerHTML = "A";

    }

  }

  if (event.target.classList.contains("disabled")) { 
    event.preventDefault();
  }

  document.getElementById("A").style.opacity = "0.5";
  event.target.classList.add("disabled");

  score = score + 1;

  document.getElementById("Score").innerHTML = score;

  }

The random word variable is a string randomly picked from a word list. Function A is an onClick event, and I will need to do the same for all the other functions, EG: function B(), C(), D().

Thanks

  • 2
    You are looking for [indexOf](http://www.w3schools.com/jsref/jsref_indexof.asp) – sam Oct 16 '15 at 00:10
  • Possible duplicate of http://stackoverflow.com/questions/4444477/how-to-tell-if-a-string-contains-a-certain-character-in-javascript – Bennett Elder Oct 16 '15 at 04:40

2 Answers2

1

You are looking for indexOf

It returns the position of the first occurrence of a specified value in a string.

This method returns -1 if the value to search for never occurs.

randomWord = "test string"
if (randomWord.indexOf("e") != -1) {
    //do stuff here
}
sam
  • 2,033
  • 2
  • 10
  • 13
  • Thanks you helped heaps: if (randomWord[letter].indexOf("a") != -1) { document.getElementById("letter_" + letter).innerHTML = "A"; } – Display Name Oct 16 '15 at 00:30
0

Try this:

function getLetter(min, max) {
    var letters = 9,//9 possibilities from what I understand
        letter = Math.random() * (letters - 1) + 1;
    eval(letter+"()");
    var el = document.getElementById(letter);
    el.style.opacity = "0.5";
    el.classList.add("disabled");
}
James
  • 1,167
  • 1
  • 13
  • 37