2

I'm trying to make it so that text will be shown under the input box with some of the letters should be replaced with underscores. This text will be the answer that the user should type in to get the correct output.

I expected the loop to replace letters like e, with the _, but it does nothing. There are no error messages, it just doesn't replace the letter e. I have tried to put a for loop, which I found on other places for how to replace certain characters from an array's element, but nothing worked.

Here is the JS code:

let array = ['blue', 'green', 'red', 'orange', 'pink', 'silver', 'purple', 'lime']
let arraySecond = ['blue', 'green', 'red', 'orange', 'pink', 'silver', 'purple', 'lime']; 

//The other array is the one that shows the element, 
//that matches the first array, but with "_", instead of certain letters

document.getElementById('check').addEventListener('click', thisFunction);

function thisFunction() {
   let value = document.getElementById('input').value;
   
   if (value == theColor) {
    alert(`Congrats you gussed right, its ${value}`)
        } else {
    alert(`Oof, your guess was incorrect, it\'s ${array[randomizedArray]}`)
    }
}

let randomizedArray = Math.floor(Math.random() * array.length);

let theColor = array[randomizedArray]; 

//One thing the code above is used for is be in the for loop, to replace letters

for (let i = 0; i < theColor.length; i++) {
    theColor[i] = theColor[i].replace('e', '_');
} 

//This loop that should do the replacing, but it doesn't work

document.getElementById('output').innerHTML = theColor;
4
  • Can you explain a bit more about what you are trying to do, e.g. do you want to replace all instances of the letter e (for example) with _ , or be able to decide whcih ones to replace? Commented Oct 4, 2020 at 2:50
  • So the program will pick a certain element in the array. Let's say blue because it's an element in the arrays. It will then replace the e with an underscore which should show it as blu_. This part is done with the second array, the first is for the user to type in the input. Commented Oct 4, 2020 at 3:00
  • Ok, I get that, but what if the word is "green"? Should it replace all the es it finds or just one? Commented Oct 4, 2020 at 3:01
  • Yeah gr__n like this Commented Oct 4, 2020 at 3:07

1 Answer 1

2

You are using the replace function on the individual letters of the word instead on the whole word - you don't need to loop through each letter to replace them.

Depending on exactly what you want to replace, you can do it as follows (using e as an example):

  • Replace the first instance of the letter: theColor.replace('e', '_');
  • Replace all instances of the letter: theColor.replace(/e/g, '_'); - note that the /.../g means do a global search and replace.
  • Case-insensitive replace: add /gi to the above theColor.replace(/e/gi, '_');

However my guess is that you will want to replace more than just one specific letter, so you can replace multiple letters in one go (e.g. a,e,i,o and u) like this:

  • Replace all instances of multiple letters: theColor.replace(/aeiou/gi, '_'); - does a case-insensitive replace for all of the letters between / and /gi with _

Examples:

var theColor = "green";
console.log("Replace first instance of e in "+theColor+": " 
            + theColor.replace('e', '_'));

var theColor = "GREeN";
console.log("Replacing all instances of e (case insensitive) in "+theColor+": " 
            + theColor.replace(/e/gi, '_'));

var theColor = "orange";
console.log("Replacing all vowels in one go in "+theColor+": "
            + theColor.replace(/[aeiou]/gi, '_'));

In your code to replace all vowels (a,e,i,o or u) for example you just need to do something like this:

document.getElementById('output').innerHTML = theColor.replace(/[aeiou]/gi, '_');

Note, don't change the value of theColor directly because that is what you are using to compare the guess to. The line above only replaces the displayed colour and not the name of the colour itself.

Working Example

let array = ['blue', 'green', 'red', 'orange', 'pink', 'silver', 'purple', 'lime']
let arraySecond = ['blue', 'green', 'red', 'orange', 'pink', 'silver', 'purple', 'lime'];

//The other array is the one that shows the element, 
//that matches the first array, but with "_", instead of certain letters
document.getElementById('check').addEventListener('click', thisFunction);

function thisFunction() {
  let value = document.getElementById('input').value;

  if (value == theColor) {
    alert(`Congrats you gussed right, its ${value}`)
  } else {
    alert(`Oof, your guess was incorrect, it\'s ${array[randomizedArray]}`)
  }
}

let randomizedArray = Math.floor(Math.random() * array.length);
let theColor = array[randomizedArray];

/* THIS IS WHERE THE NEW CODE IS
   DISPLACE THE COLOR WITH ALL a,e,i,o OR u REPLACED WITH _ */
document.getElementById('output').innerHTML = theColor.replace(/[aeiou]/gi, '_');
<input id="input">
<button id="check">Check</button>
<div id="output"></div>

Reference: MDN Docs for replace function

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the help and the explanation it works!
@DanAmazing Glad to help! I saw a notification for a comment about what is passed into the replace function, but it seems to have been deleted. I assume you found the answer but if not, the replace function can take a regex pattern e.g. /abc/g - you can find out more about the replace function in the docs linked to in the answer (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…) and that page it also includes a link to RegExp for more info about the regex pattern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.