So for my cit class I have to write a pig Latin converter program and I\'m really confused on how to use arrays and strings together. The rules for the conversion are simpl
this is my solution code :
function translatePigLatin(str) {
var vowel;
var consonant;
var n =str.charAt(0);
vowel=n.match(/[aeiou]/g);
if(vowel===null)
{
consonant= str.slice(1)+str.charAt(0)+”ay”;
}
else
{
consonant= str.slice(0)+”way”;
}
var regex = /[aeiou]/gi;
var vowelIndice = str.indexOf(str.match(regex)[0]);
if (vowelIndice>=2)
{
consonant = str.substr(vowelIndice) + str.substr(0, vowelIndice) + ‘ay’;
}
return consonant;
}
translatePigLatin(“gloove”);
Your friends are the string function .split
, and the array functions .join
and .slice
and .concat
.
warning: Below is a complete solution you can refer to once you have finished or spent too much time.
function letters(word) {
return word.split('')
}
function pigLatinizeWord(word) {
var chars = letters(word);
return chars.slice(1).join('') + chars[0] + 'ay';
}
function pigLatinizeSentence(sentence) {
return sentence.replace(/\w+/g, pigLatinizeWord)
}
Demo:
> pigLatinizeSentence('This, is a test!')
"hisTay, siay aay esttay!"
This code is basic, but it works. First, take care of the words that start with vowels. Otherwise, for words that start with one or more consonants, determine the number of consonants and move them to the end.
function translate(str) {
str=str.toLowerCase();
// for words that start with a vowel:
if (["a", "e", "i", "o", "u"].indexOf(str[0]) > -1) {
return str=str+"way";
}
// for words that start with one or more consonants
else {
//check for multiple consonants
for (var i = 0; i<str.length; i++){
if (["a", "e", "i", "o", "u"].indexOf(str[i]) > -1){
var firstcons = str.slice(0, i);
var middle = str.slice(i, str.length);
str = middle+firstcons+"ay";
break;}
}
return str;}
}
translate("school");
Yet another way.
String.prototype.toPigLatin = function()
{
var str = "";
this.toString().split(' ').forEach(function(word)
{
str += (toPigLatin(word) + ' ').toString();
});
return str.slice(0, -1);
};
function toPigLatin(word)
{
//Does the word already start with a vowel?
if(word.charAt(0).match(/a*e*i*o*u*A*E*I*O*U*/g)[0])
{
return word;
}
//Match Anything before the firt vowel.
var front = word.match(/^(?:[^a?e?i?o?u?A?E?I?O?U?])+/g);
return (word.replace(front, "") + front + (word.match(/[a-z]+/g) ? 'a' : '')).toString();
}