Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly replace() on a string

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'

like image 516
pauld Avatar asked Aug 16 '26 18:08

pauld


1 Answers

You don't need a loop here, just use standard regex multiple selectors, e.g. see the following:

'cherrych'.replace(/^[^aeiou]*/, '')
like image 105
smnbbrv Avatar answered Aug 19 '26 11:08

smnbbrv