[Pig Latin Algorithm][SOLVED] Why does this regex return an empty string?

arr = 'guitar'.split(/([aeiou].*)/);

^ This code logs this to the console: `Array [ "g", "uitar", "" ]`

Why is there an empty string, `""`, at `arr[2]`?

I expected just two elements when the string is split.

Because you are splitting on uitar.
So you are getting g on one side and '' on the other. And as you are using capturing in your regex (parenthesis) you get you capture group also included in the returned array.

Try this:


Ah, now I feel silly.

This is actually for the Pig Latin algorithm. I don’t think your suggestion in this situation, but I solved it prior to asking. Sorry for not giving the full context in the beginning.

I just wanted to fully understand my code, so thank you for the explanation. I posted it below in case you were curious.

  var arr = [];
  var part = 'banana'.split(/([aeiou].*)/);
  if ((/[b-df-hj-np-tv-z]/).test(str[0])) {
    arr = str.split(/([aeiou].*)/);
    return arr[1] + arr[0] + 'ay';
      } // close if
  else {
    return str + 'way';
  } // close else
} // close function```

My example was just to illustrate what happens when you split :wink: It wasn’t a recommendation to improve your code.

And now I’ll make some recommendations :nerd: :

  • to select consonant in regex you can use [^aeiou] - select not vowels
  • as you are using arr only in if you can declare and assign it on the same line
  • as you are returning from if you don’t need else
  • var part ... I suppose was for testing :slight_smile:
function translatePigLatin(str) {
  if ((/[^aeiou]/).test(str[0])) {
    var arr = str.split(/([aeiou].*)/);
    return arr[1] + arr[0] + 'ay';
  return str + 'way';
1 Like

Thank you jenovs :grinning: ! Your recommendations were easy to understand. I swear you’ve answered like half of my questions on this site haha.