Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
JavaScript Pig Latin Converter Optimizations

Total newb here...looking for some examples of optimizing this pigLatin converter.

function pigLatin(str) {

  var vowels = ["A", "E", "I", "O", "U", "a", "e", "i", "o", "u"];
   if (vowels.includes(str[0])) {
    str = str + "way";
    return str;
  }
 
  for (i = 0; i < str.length; i++) {
    if (vowels.includes(str[i])) {
      var flopStr = str.substring(0, [i]) + "ay";
      var newStr = str.substring([i]) + flopStr;
      return newStr;
    }
  }
  
  if (!vowels.includes(str) === true) {
    str = str + "ay";
    return str;
  }
}

I am pretty happy that I can at least write something that works. I do; however, need some guidance on other methods of accomplishing the same task.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This is a solution without any looping, working with a regex and the index of the first vowel

function pigLatin(str) {

  let lC = str.toLowerCase()
  
  const vowels = ["a", "e", "i", "o", "u"];
  
  let regex = /[aeiou]/
  
  let fVI = lC.search(regex) // firstVowelIndex
  
  switch(fVI) {
    case 0: 
      return lC+'way';
    default:
      return lC.substring(fVI) + lC.substring(0,fVI) + 'ay'
  }
}

console.log(pigLatin('coding'))  // 'odingcay'

console.log(pigLatin('addict'))  // addictway

(an improvement you could adopt in your version is to convert the string to lower case and remove uppercase vowels from the array)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!