I’m working on a codecademy exercise where we’re building a hangman game with jQuery/JavaScript. The player starts with a string of underline characters ‘‘ and if they guess a letter in the word, the appropriate underline should be replaced with that letter. For example, if the word is ‘tree’ and the player guesses ‘e’, the function should return ‘_ee’
I wrote the function using gsub. N is the position where the string is supposed to be alterned, and c is the character to insert at that position on the original string. This passes the test at codecademy.
function alterAt ( n, c, originalString ) {
var k = originalString.gsub(n, c );
return k;
}
However, codecademy told me to use the function substr() and concatenation to return a new string with the letter replaced. I can’t figure out how to do it this way, and I’m not even sure if it’s the better way to do it. What’s wrong with using gsub? Can you assist?
Here’s a version using
substr():Working demo: http://jsfiddle.net/jfriend00/YX94Q/
If, in the context of your hangman game, you had two strings, one the original and one the underscores plus guessed letters and you wanted to apply a guess to the underscores, you could do that like this:
Working demo: http://jsfiddle.net/jfriend00/EwfxW/.