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
I think the two things you really need to be looking at are the substring()
method and string concatentation (adding two strings together) in general. Being that all of the objects in the array returned from your call to split()
are strings, simple string concatentation works fine. For example, using these two methods, you could move the first letter of a string to the end with something like this:
var myString = "apple";
var newString = mystring.substring(1) + mystring.substring(0,1);
Here's my solution
function translatePigLatin(str) {
var newStr = str;
// if string starts with vowel make 'way' adjustment
if (newStr.slice(0,1).match(/[aeiouAEIOU]/)) {
newStr = newStr + "way";
}
// else, iterate through first consonents to find end of cluster
// move consonant cluster to end, and add 'ay' adjustment
else {
var moveLetters = "";
while (newStr.slice(0,1).match(/[^aeiouAEIOU]/)) {
moveLetters += newStr.slice(0,1);
newStr = newStr.slice(1, newStr.length);
}
newStr = newStr + moveLetters + "ay";
}
return newStr;
}
Another way of doing it, using a separate function as a true or false switch.
function translatePigLatin(str) {
// returns true only if the first letter in str is a vowel
function isVowelFirstLetter() {
var vowels = ['a', 'e', 'i', 'o', 'u', 'y'];
for (i = 0; i < vowels.length; i++) {
if (vowels[i] === str[0]) {
return true;
}
}
return false;
}
// if str begins with vowel case
if (isVowelFirstLetter()) {
str += 'way';
}
else {
// consonants to move to the end of string
var consonants = '';
while (isVowelFirstLetter() === false) {
consonants += str.slice(0,1);
// remove consonant from str beginning
str = str.slice(1);
}
str += consonants + 'ay';
}
return str;
}
translatePigLatin("jstest");
function translate(str) {
str=str.toLowerCase();
var n =str.search(/[aeiuo]/);
switch (n){
case 0: str = str+"way"; break;
case -1: str = str+"ay"; break;
default :
//str= str.substr(n)+str.substr(0,n)+"ay";
str=str.replace(/([^aeiou]*)([aeiou])(\w+)/, "$2$3$1ay");
break;
}
return str;
}
translate("paragraphs")
Another way of Pig Latin:
function translatePigLatin(str) {
let vowels = /[aeiou]/g;
var n = str.search(vowels); //will find the index of vowels
switch (n){
case 0:
str = str+"way";
break;
case -1:
str = str+"ay";
break;
default:
str = str.slice(n)+str.slice(0,n)+"ay";
break;
}
return str;
}
console.log(translatePigLatin("rhythm"));
If you're struggling with arrays this might be a bit complicated, but it's concise and compact:
var toPigLatin = function(str) {
return str.replace(/(^\w)(.+)/, '$2$1ay');
};
Demo: http://jsfiddle.net/elclanrs/2ERmg/
Slightly improved version to use with whole sentences:
var toPigLatin = function(str){
return str.replace(/\b(\w)(\w+)\b/g, '$2$1ay');
};