A challenge question "Given is a string hangmanString. Replace every second letter with an underscore and return the result as a string. The first character must be an underscore.".
My result kept repeating the words and adding the underscore in each words. I have attached a screenshot of my solution for better understanding.enter image description here
function hangman(hangmanString) {
var result = "";
var replacement = "";
for(let i = 0; i < hangmanString.length; i++){
if(i % 2 === 0){
replacement = hangmanString.replace(hangmanString[i], "_");
result = result + replacement;
}
}
return result;
}
hangman("TestString");
Any suggestion what the issue might be?
2
Answers
Every time this if clause
if(i % 2 === 0){
is true:This part of the code is giving you the hangmanString string with a replacement:
replacement = hangmanString.replace(hangmanString[i], "_");
And then you concatenate it to the result making the result longer
result = result + replacement;
You could use a single variable instead and concatenate either the underscore or the current character.
If this is true
i % 2 === 0
then return an underscore to make it the first character.There are of course other ways to write this implementation. If you are interested, here is one other possibility using Array.from where the second parameter is the map function have the current element as the first parameter and the index as the second parameter.
The
Array.prototype.map()
function can be passed acallbackfn
which gives you access to theindex
so you could:String.prototype.split()
.Array.prototype.map()
method and return either an underscore or the element depending on it’s index modulus.Array.prototype.join()
.It might look like this: