Reputation: 421
I am trying to use replace with a while loop. I want to replace the first letter in the string with an empty string if the letters is not a vowel. The regex I have used is working because the letters are added to the end of the string, just not sure what is happening with the replace function?
Here is my code:
vowel = new RegExp("[aeiou]");
word = "cherry";
var moved = '',
i = 0;
while (!vowel.test(word[i])) {
moved += word[i];
word.replace(word[i], '');
i++;
}
return word+moved;
For example, 'cherrych' will be returned rather than 'errych'
Upvotes: 3
Views: 54
Reputation: 9846
String.prototype.replace
returns a modified copy of the string, and does not alter the string in place.
Every time you do word.replace()
, you cause a new string to be returned but importantly word
is not altered at all.
The right way to attack this is then to assign this new modified copy to the original by
word = word.replace(word[i],'');
Upvotes: 2
Reputation: 24581
You don't need a loop here, just use standard regex multiple selectors, e.g. see the following:
'cherrych'.replace(/^[^aeiou]*/, '')
Upvotes: 3