First problem: your arguments to
the slice
method[
^] are wrong. The first argument needs to be the start index, and the second argument is the end index.
firstPart = word.slice(0, i - 1);
secondPart = word.slice(i + 1);
Secondly, when you're using a
for
loop to iterate over a sequence, and you're modify that sequence within the loop, you need to iterate backwards; otherwise, you end up missing items.
Consider the input
"feed"
:
word[0] === "f"
is not a vowel; the word is unchanged.word[1] === "e"
is a vowel; the word is changed to "fed"
.word[2] === "d"
is not a vowel; the word is unchanged.
The end result is
"fed"
, which is obviously not what you wanted.
If you reverse the iteration -
for (let i = word.length - 1; i >= 0; i--)
:
word[3] === "d"
is not a vowel; the word is unchanged.word[2] === "e"
is a vowel; the word is changed to "fed"
.word[1] === "e"
is a vowel; the word is changed to "fd"
.word[0] === "f"
is not a vowel; the word is unchanged.
The end result is now
"fd"
.