1

I have hit a block in working on an assignment. How do I insert a value to a given index or indices?

For example, I'm working on a hangman game. If the word is "harry", and the player guesses the letter "r" how do I turn my array of underscores to "_ _ r r _"?

what I have below gets a word from a separate js file, creates an array of underscores (one for each letter of the returned word), and then, when a user guesses a letter, it finds the index or indices of the occurrences of that letter.

**I've updated the code below. The for loop towards the end goes my array of underscores (wordToGuess[]) and splices in the users input. This does what I need it but it also puts the last guessed letter in the front. For example if the word was "bold" and the last letter the user guessed was "l", the wordToGuess array would be lbold. Does anyone here know why this is? I'm sure its something easy I'm overlooking, but its driving me nuts.

Javascript

var word;

$(document).ready(function () {
    SetGameBoard();
});

//When guess button is clicked
$('#BtnGuess').click(function () {
    CheckGuess();
});

function GetPhrase() {
    word = ReturnWord();
    alert(word);
}

function SetGameBoard() {
    GetPhrase();
    wordToGuess = new Array(word.length);

     // Place underscore for each letter in the answer word in the DivWord div
    for (var i = 0; i < word.length; i++){
       wordToGuess[i] = "_ ";
     }
    $('#DivWord').html(wordToGuess);
}


function CheckGuess() {
    var pos = 0;
    var posArray = [];
    var guessLetter = $('#tbGuessLetter').val();

    while ((pos = word.indexOf(guessLetter, pos)) > -1) {
        posArray.push(++pos);
    }

    if (posArray.length == 0) {
        alert(guessLetter + " is not in the word.");
    }

    //Splice in correct letters. Not working 100%
    for(i=0; i < wordToGuess.length; i++){
        wordToGuess.splice(posArray[i], 1, guessLetter);
        }
        $('#DivWord').html(wordToGuess);

    alert(posArray);

    alert(guessLetter);
}
exeleon
  • 121
  • 2
  • 14
  • check this out: http://www.openjs.com/scripts/strings/setcharat_function.php – Akhilesh Sharma Dec 05 '14 at 19:14
  • where is "ReturnWord()" set? – user3871 Dec 05 '14 at 19:19
  • @Growler its located in a separate file, which is just an array of words and a function to "randomly" select one of the words and return it. – exeleon Dec 05 '14 at 19:22
  • @exeleon _"If the word is "harry", and the player guesses the letter "r" how do I turn my array of underscores to **"_ _ r r _"**?""_ If a single (_one_) `r` is guessed correctly , _two_ `r`'s are revealed at masked word ? – guest271314 Dec 05 '14 at 19:35

4 Answers4

2

Try something like this:

var word=["_","_","
_"];
word[1]="r";

now your array becomes ,1,

stranger4js
  • 269
  • 4
  • 15
0

For modifying arrays in place, you want Array.prototype.splice()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

From the docs:

var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];

// removes 0 elements from index 2, and inserts 'drum'
var removed = myFish.splice(2, 0, 'drum');
// myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon']
// removed is [], no elements removed

// removes 1 element from index 3
removed = myFish.splice(3, 1);
// myFish is ['angel', 'clown', 'drum', 'surgeon']
// removed is ['mandarin']

// removes 1 element from index 2, and inserts 'trumpet'
removed = myFish.splice(2, 1, 'trumpet');
// myFish is ['angel', 'clown', 'trumpet', 'surgeon']
// removed is ['drum']

// removes 2 elements from index 0, and inserts 'parrot', 'anemone' and 'blue'
removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
// myFish is ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon']
// removed is ['angel', 'clown']

// removes 2 elements from index 3
removed = myFish.splice(3, Number.MAX_VALUE);
// myFish is ['parrot', 'anemone', 'blue']
// removed is ['trumpet', 'surgeon']

It looks like the behavior you want is in the third example here where they replace 'drum' with 'trumpet'.

Neil Sarkar
  • 6,834
  • 8
  • 32
  • 30
0

Edit, Updated

Try

var word = "word" // `word` : input `String`
    , _word = word.split("")
    , mask = word.replace(/./g, "_")
    , _mask = mask.split("")
    , temp = ""
    , guess = function (letter) {
         _mask[
             $.inArray(
                 letter
                 , _word
                 , temp.match(letter) !== null 
                   ? temp.lastIndexOf(letter) + 1 
                   : 0
             )
         ] = letter;
         temp = _mask.join("");
         return temp.indexOf("_") !== -1 ? temp : word
     };

 $("input").on("input", function (e) {
     $("#results").text(guess(e.target.value));
     e.target.value = "";
 });

var word = "word" // `word` : `String`
    , _word = word.split("")
    , mask = word.replace(/./g, "_")
    , _mask = mask.split("")
    , temp = ""
    , guess = function (letter) {
         _mask[
             $.inArray(
                 letter
                 , _word
                 , temp.match(letter) !== null 
                   ? temp.lastIndexOf(letter) + 1 
                   : 0
             )
         ] = letter;
         temp = _mask.join("");
         return temp.indexOf("_") !== -1 ? temp : word + " !"
     };

 $("input").on("input", function (e) {
     $("#results").text(guess(e.target.value));
     e.target.value = "";
 })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" />
<div id="results"></div>
guest271314
  • 1
  • 15
  • 104
  • 177
-1

Do something like

string replaceAt = function(str, index, character) {
    return str.substr(0, index) + character + str.substr(index+character.length);
}

hangmanString = replaceAt(hangmanString, 3, 'r');

Shamelessly stolen from here.

Community
  • 1
  • 1
Paul
  • 646
  • 4
  • 13
  • 1
    You may want to reference where you got this code from: http://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript – user3871 Dec 05 '14 at 19:44
  • 1
    Busted! Added a link. – Paul Dec 05 '14 at 20:02