I've got a Pig Latin translator that I've set up to take single or multi-word strings, but it can't do punctuation.
As it is, translatePigLatin("Pig Latin");
returns 'Igpay Atinlay'
, as it should, but translatePigLatin("Pig Latin.");
returns 'Igpay Atin.lay'
, with the period annoyingly in the middle of a word. How do I make it return 'Igpay Atinlay.'
instead?
The function is:
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();
});
}
You could use this function:
function punct(str)
{
var punctuation = ".,!@#$";
var matches = 0;
for(var i=0;i<str.length-matches;i++)
{
if(punctuation.indexOf(str[i])!=-1)
{
str = str.substr(0,i) + str.substr(i+1)+str[i--];
matches++;
}
}
return str;
}
which loops through your string using a for loop and if it finds a character within the punctuation string, it moves that character at the end of the string.So punct("Igpay Atin.lay") yields "Igpay Atinlay.".Give it a shot.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.