Search code examples
javascriptarraysperformancejavascript-objects

How do i replace letters with underscores but let the spaces stay in javascript


i am trying to replace the letters i get from the word with underscores but if there is any spaces in that word i do not want to replace it. im not sure how to do it. the current code i am using is this answerArray = [] function randomWord() {

    for (let i = 0; i < word.length; i++) {
        answerArray[i] = "_"
        answer.innerHTML = answerArray.join(" ")
    }
}

i've tried to look around in stackoverflow with my question but no one has it. someones suggested this

word.replace(/\w/gi, '_')

but it isnt working as i want.

You can check out the code here https://codepen.io/NoNameYet04/pen/OJxKYeV i have for the test change the word in "programming language" to "test test" so you can test it out


Solution

  • function randomWord() {
      for (let i = 0; i < word.length; i++) {
        answerArray[i] = word[i] == " " ? "&nbsp;" : "_"; // <==
        console.log(answerArray[i]);
        answer.innerHTML = answerArray.join(" ")
      }
    }
    

    Explanation: Is the current character you're iterating a space in the word? If yes we insert a space (in this case an HTML space), if not we just insert an underscore.

    Also, don't forget to change the assignment of the variable remainingLetters in your category() function so you're ignoring the space.

    function category(type) {
      /* ... */
      remainingLetters = word.replace(/ /g, "").length;
      /* ... */
    }