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
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:
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 withindexOf()
: