My Pig Latin converter works well with single or multi-word strings, but it struggles with punctuation marks.
For example, when I input translatePigLatin("Pig Latin.");
, the output is 'Igpay Atin.lay'
instead of 'Igpay Atinlay.'
. How can I modify the function to handle this correctly?
This is the current function:
function translatePigLatin(string) {
var arr = string.split(' ');
var str;
for (var i = 0; i < arr.length; i++) {
var j = 0;
if (!/[\d]/.test(arr[i])) {
while (/[^aeiou]/i.test(arr[i][j])) {
j++;
}
if (j > 0) {
arr[i] = arr[i].slice(j) + arr[i].slice(0, j) + 'ay';
} else {
arr[i] = arr[i] + 'way';
}
}
if (/[A-Z]/.test(arr[i])) {
arr[i] = toTitleCase(arr[i]);
}
}
return arr.join(' ');
}
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}