function betterPigLatin(string) {
var num = 1;
let arr = string.split(’ ‘)
for (let i = 0; i < arr.length; i++) {
let word = arr[i];
arr[i] = word.substring(num) + word.substring(0, num) + ‘ay’;
}
return arr.join(’ ');
};
This seems to work very well other than with punctuation within the string. I am confused about how to write the code to segment out the punctuation while maintaining the sentence structure. Any tips from the pros on a better way?
Create an array with punctuation characters. Check if a word ends in punctuation using the array - if it has punctuation log it and drop it from the word, then when you’re done scrambling the word you can add the punctuation back to the end.
My solution
for (let i = 0; i < arr.length; i++) {
let word = arr[i];
let punctuationValue; // Store punctuation here if we find one.
let punctuationArray = ['.', ',', '?','!']; // Array of punctuation to check for
for(char of punctuationArray) { // check each element in the array
if(word.endsWith(char)) { // if it ends in punctuation
word = word.slice(0, word.length - 1); // cut it out
punctuationValue = char; // save the punctuation mark
}
}
arr[i] = word.substring(num) + word.substring(0, num) + 'ay';
if (punctuationValue) {
arr[i] += punctuationValue; // add punctuation back to the end of the word
}
}
...
console.log(betterPigLatin('This is a test, or is it? I think it is. Hope it works!'));
// hisTay siay aay esttay, roay siay tiay? Iay hinktay tiay siay. opeHay tiay orksway!
If you want to fix the capital letters, it might be easier to split the array into sentences (split by punctuation marks instead of " "), put it all toLowerCase() and then capitalize the first letter of the first word.
Here’s an article I found on capitalizing the first letter: