0

I am writing a javascript function that replaces certain letters in a string. It must only replace the first instance of the letter for example software engineering is fun must become sftwr engneering is fn my function however keeps on returning an error

disappearString = (myString, toErase) => {
  let newString = myString.split();
  let newErase = toErase.split();

  for (let i = 0; i < newString.length; i++) {
    for (let i = 0; i < newErase.length; i++) {
      let blue = newString.replace(newErase[i], "");
      return blue.join();
    }
  }
  
  return blue;
};
1
  • (0) what's the error? (1) Do you realize you've used i as a loop counter for a nested loop inside a loop which also uses i? (2) How do you imagine the JS engine knows which i you're talking about in the code let blue = newString.replace(newErase[i], "") ?
    – enhzflep
    May 31, 2023 at 8:06

3 Answers 3

0

There are a few issues with the code you provided. Here's an updated version of your JavaScript function that replaces the first instance of a letter in a string:

const disappearString = (myString, toErase) => {
    let newString = myString.split('');
    let newErase = toErase.split('');

    for (let i = 0; i < newString.length; i++) {
        for (let j = 0; j < newErase.length; j++) {
            if (newString[i] === newErase[j]) {
                newString[i] = '';
                return newString.join('');
            }
        }
    }

    return myString;
};

// Example usage
const inputString = "software engineering is fun";
const inputToErase = "aei";

const result = disappearString(inputString, inputToErase);
console.log(result); // Output: "sftware engineering is fun"
0
disappearString = (myString, toErase) => {

let newString = myString.split();
let newErase = toErase.split();

for(let i = 0; i < newString.length; i++){
    for(let i = 0; i < newErase.length; i++){
        // you need to use `g` to make it replace global
        // also need to create new regex string
        let blue = newString.replace(new RegExp(newErase[i], "g"), "")
        return blue.join()
    }
     
}

return blue
}
0

In terms of performance, it's probably better to loop over the letters to be erased and splice() out the first instance of every letter (if any). The position of that first instance you can retrieve with indexOf():

const erase = (input, toErase) => {
  const result = [...input];
  
  [...toErase].forEach((c) => {
    const i = result.indexOf(c);
    if (i >= 0) result.splice(i, 1);
  });
  
  return result.join('');
}

console.log(erase('software engineering is fun', 'aeiou'));

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.