Error trying to find the first letter and the first vowel

1

I saw another question that I was trying to solve as, of any word, always show the first letter and the first vowel, that is:

"mapita" -> ma    
"astro" -> ao

function palabra(w){
  var toArray = w.split(""),
      regex = /aeiou/i,
      i = 1,
      m = toArray.length,
      finalmente = [];
  for(;i<m;i++){
    if(regex.test(toArray[i])) {
      
      finalmente.push(toArray[0] + toArray[i]).join("");
      break;
  }  
  }
  return finalmente;
};

console.log(palabra("astronauta"))

But I do not understand what my mistake is, why does not it work?

    
asked by Eduardo Sebastian 19.10.2017 в 16:43
source

2 answers

3

The main reason is your regex. You are saying that you compare your letter with "aeiou" not with any of those vowels.

That's why your regex should be /[aeiou]/i .

Also, you do not need to make a loop and go looking at each of them.

You can do a replace of the consonants by "" to keep the vowels. The regex would be like the previous one but with a ^ that is a NOT.

It would remain /[^aeiou]/gi adding the flag g to be a global replace. (note: you have to add more characters if you are going to deal with accents)

Then you only have to print the first character and the first vowel, taking into account that if the first vowel is the first letter, you take the second vowel (that seems to be happening in your "astro" test)

function palabra(w) {

  var regex = /[^aeiou]/gi;
  var vowels = w.replace(regex, "");
  var len =  vowels.length;
  if(len > 1)
      console.log(w[0] + (vowels[0] == w[0] ? vowels[1] : vowels[0]));
  else
    console.log(w[0]);
}



palabra("astronauta")
palabra("mapita")
palabra("sr.")
palabra("al");
    
answered by 19.10.2017 / 17:01
source
3

Accept the response from lois6b that describes the problem of your question well.

I add that this can be solved with a single regular expression that captures both:

function primera(w) {

  let regex = /^.*?([a-záéíóúüñ])(?:.*?([aeiouáéíóúü]))?/i,
      resultado = w.match(regex);

  if (resultado) {
    return {
      letra: resultado[1],
      vocal: resultado[2]
    }
  }
}


//Pruebas
for (let prueba of ['astronauta', 'mapita', 'y', 'dr']) {
  console.log(primera(prueba));
}

Description:

/^.*?([a-záéíóúüñ])(?:.*?([aeiouáéíóúü]))?/i
  • ^ - start of the text.
  • .*? - any number of characters, the less necessary (in case there is a character other than a letter at the beginning).
  • ([a-záéíóúüñ]) - first group, so it captures the text with which it matches in resultado[1] . Matches:
    One letter.
  • (?:.*?([aeiouáéíóúü]))? - is an optional group (in case you do not have a vowel after the first letter). Coincides with:
    • .*? - any number of characters, how many less are necessary.
    • ([aeiouáéíóúü]) - Group 2 that captures in resultado[2] . Matches:
      A vowel.
  • /i - ignores lowercase and uppercase.
answered by 19.10.2017 в 17:55