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 simple, you just move the first letter of the word to the back and then add ay. ex: hell in English would be ellhay in pig Latin I have this so far:
<form name="form">
<p>English word/sentence:</p> <input type="text" id="english" required="required" size="80" /> <br />
<input type="button" value="Translate!" onClick="translation()" />
<p>Pig Latin translation:</p> <textarea name="piglat" rows="10" cols="60"></textarea>
</form>
<script type="text/javascript">
<!--
fucntion translation() {
var delimiter = " ";
input = document.form.english.value;
tokens = input.split(delimiter);
output = [];
len = tokens.length;
i;
for (i = 1; i<len; i++){
output.push(input[i]);
}
output.push(tokens[0]);
output = output.join(delimiter);
}
//-->
</script>
I'd really appreciate any help I can get!
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 simple, you just move the first letter of the word to the back and then add ay. ex: hell in English would be ellhay in pig Latin I have this so far:
<form name="form">
<p>English word/sentence:</p> <input type="text" id="english" required="required" size="80" /> <br />
<input type="button" value="Translate!" onClick="translation()" />
<p>Pig Latin translation:</p> <textarea name="piglat" rows="10" cols="60"></textarea>
</form>
<script type="text/javascript">
<!--
fucntion translation() {
var delimiter = " ";
input = document.form.english.value;
tokens = input.split(delimiter);
output = [];
len = tokens.length;
i;
for (i = 1; i<len; i++){
output.push(input[i]);
}
output.push(tokens[0]);
output = output.join(delimiter);
}
//-->
</script>
I'd really appreciate any help I can get!
Share Improve this question edited Aug 26, 2014 at 0:36 OneHoopyFrood 3,9593 gold badges27 silver badges39 bronze badges asked Apr 24, 2012 at 22:24 GcapGcap 3786 gold badges11 silver badges26 bronze badges 7- The first step to solving the problem is learning to ask the right question. What exactly is confusing to you? You might just find you that you find the tools to answer your own question. – J. Holmes Commented Apr 24, 2012 at 22:30
-
1
Doesn't answer your question, but note that you're creating global variables for
input
,tokens
,output
,len
, andi
in yourtranslation
function (the wordfucntion
[sic] is also misspelled, but at least you'll get an error for that in the console). You've declareddelimiter
usingvar
, but the;
at the end of that ends thevar
statement, so the following several statements are just assignments (except fori;
) in which you fall prey to The Horror of Implicit Globals. Just FWIW. – T.J. Crowder Commented Apr 24, 2012 at 22:35 - @32bitkid I'm confused on how to move letters around in an array I guess.. I know how to separate the first letter from the word but not how to move it at the end – Gcap Commented Apr 24, 2012 at 22:37
- Please var all of your variables.. we dont want global scope hoarding – rlemon Commented Apr 24, 2012 at 22:39
-
@Gcap: There's no need to move letters in an array. Once you have the array of strings for the words, which you're correctly getting (other than the things in my note above) from
split
, look at usingString#substring
. – T.J. Crowder Commented Apr 24, 2012 at 22:43
10 Answers
Reset to default 5function 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")
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);
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");
If you're struggling with arrays this might be a bit plicated, but it's concise and pact:
var toPigLatin = function(str) {
return str.replace(/(^\w)(.+)/, '$2$1ay');
};
Demo: http://jsfiddle/elclanrs/2ERmg/
Slightly improved version to use with whole sentences:
var toPigLatin = function(str){
return str.replace(/\b(\w)(\w+)\b/g, '$2$1ay');
};
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");
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”);
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();
}
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"));
Your friends are the string function .split
, and the array functions .join
and .slice
and .concat
.
- https://developer.mozilla/en/JavaScript/Reference/Global_Objects/Array#Accessor_methods
- https://developer.mozilla/en/JavaScript/Reference/Global_Objects/String#Methods_unrelated_to_HTML
warning: Below is a plete 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!"