skip to Main Content

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
}

3

Answers


  1. 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
    }
    
    Login or Signup to reply.
  2. 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"
    
    Login or Signup to reply.
  3. 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'));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search