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

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

#1
arr = 'guitar'.split(/([aeiou].*)/);
console.log(arr);```

^ 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.

#2

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:

console.log('g'.split('g'));

#3

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```

#4

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';
}

#5

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