DEV Community

Discussion on: Algorithm 101: 3 Ways to Create Pig Latin

Collapse
 
lexlohr profile image
Alex Lohr • Edited

Here's what I would have come up with:

const splitWord = /([bcdfghjklmnpqrstvwxyz]*)([a-z]*)([^a-z]*)/g;
const pigLatin = (word) => word.toLowerCase().replace(
  splitWord,
  (_, firstConsonants, rest, nonWordSuffix) => `${rest}${firstConsonants || 'w'}ay${nonWordSuffix}` 
)

First, we use a regular expression to separate the first consonants, the remaining word and subsequent non-word-characters in each word of any sentence (the latter being useful so we don't have to take care about word boundaries - but it can be left away if you only want to translate single words).

Then we use the replace method with a callback to recombine these matches to the intended result using a template string. We need the callback to ensure that words not starting with a consonant will end in 'way'.

Collapse
 
ebereplenty profile image
NJOKU SAMSON EBERE

Alex, thank you for this solution. I love the simplicity and I am definitely checking it out 👏🏼