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.
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'));
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 It wasn’t a recommendation to improve your code.
And now I’ll make some recommendations :
- to select consonant in regex you can use
[^aeiou]
- select not vowels - as you are using
arr
only inif
you can declare and assign it on the same line - as you are
return
ing fromif
you don’t needelse
-
var part ...
I suppose was for testing
function translatePigLatin(str) {
if ((/[^aeiou]/).test(str[0])) {
var arr = str.split(/([aeiou].*)/);
return arr[1] + arr[0] + 'ay';
}
return str + 'way';
}
Thank you jenovs ! Your recommendations were easy to understand. I swear you’ve answered like half of my questions on this site haha.