skip to Main Content

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


  1. 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 truei % 2 === 0 then return an underscore to make it the first character.

    function hangman(hangmanString) {
      let result = "";
    
      for (let i = 0; i < hangmanString.length; i++) {
        result += (i % 2 === 0) ? "_" : hangmanString[i];
      }
      return result;
    }
    console.log(hangman("TestString"));

    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.

    const hangman = s => Array.from(s, (elm, idx) => idx % 2 ? elm : '_').join('');
    
    console.log(hangman("TestString"));
    Login or Signup to reply.
  2. The Array.prototype.map() function can be passed a callbackfn which gives you access to the index so you could:

    1. Transform the string to an array with String.prototype.split().
    2. Map over the array elements calling it’s Array.prototype.map() method and return either an underscore or the element depending on it’s index modulus.
    3. Then join the array back together using Array.prototype.join().

    It might look like this:

    function hangman(hangmanString) {
      return hangmanString.split("").map((el, ix) => {
         return ix % 2 === 0 ? '_' : el
      }).join("");
    }
    const str = hangman("TestString");
    console.log(str)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search