skip to Main Content

I want to remove the consonants in a string until I get to a vowel. For example the string "glove", the results should be "ove".

This was my attempt but it will only remove the first consonant.

var newStr = str.split("").splice(1, ).join("");
var removeLetter = str.split("").shift();

2

Answers


  1. Well, in order to do something until you need a loop. First, break your input string "glove" into a char array using .split(''), then check for each char whether it matches any of your defined vowels (['a', 'e', 'i', 'o', 'u']). When the first vowel has been found you break the process, put your chars back together using .join() and return your result.

    const isVowel = char =>
      ["a", "e", "i", "o", "u"].includes(char.toLowerCase());
    
    const removeConsonantsUntilVowel = str => {
      let foundVowel = false;
    
      return str
        .split("")
        .filter(char =>
          !foundVowel
            ? !isVowel(char)
              ? false
              : (foundVowel = true)
            : true
        )
        .join("");
    };
    
    const result = removeConsonantsUntilVowel("glove");
    console.log(result);
    Login or Signup to reply.
  2. You can use a function to delete all words until your condition.

    function removeConsonantsUntilVowel(str) {
      const vowels = 'aeiouAEIOU';
      let index = 0;
    
      for (let i = 0; i < str.length; i++) {
        if (vowels.includes(str[i])) {
          index = i;
          break;
        }
      }
    
      return str.substring(index);
    }
    
    const word = "glove";
    const result = removeConsonantsUntilVowel(word);
    console.log(result);
    

    But if you do not want that way, this is other way you can do it.

    const vowels = 'aeiouAEIOU';
    let index = 0;
    const str2 = "GLOVE"
    
    for (let i = 0; i < str2.length; i++) {
      if (vowels.includes(str2[i])) {
        index = i;
        break;
      }
    }
    console.log(str2.substring(index))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search