Translate your text into Pig Latin by adding an ‘ay’ syllable to the end of each word, with special rules for vowels and consonant clusters.
export const make = (text) => {
const leadingVowel = /^([aeiouy]|[^aeiouy]+$)/i
const leadingY = /^y/i
const trailingY = /y$/i
const fromFirstVowel = /[aeiouy].*$/i
const toFirstVowel = /[^aeiouy]+/i
return text
.split(/\b/g)
.map((token) => {
if (!/[a-z]/i.test(token)) return token
// Is this a standard case, or is there a leading vowel?
let [front, back] = leadingVowel.test(token)
? [token, "yay"]
: [token.match(fromFirstVowel)[0], token.match(toFirstVowel)[0] + "ay"]
// Special case for y
if (front.length > 1 && leadingY.test(front) && leadingY.test(back)) {
front =
front[0] === "y"
? front.slice(1)
: front.slice(1, 2).toUpperCase() + front.slice(2)
}
// Flip capitalisation
if (back[0] !== back[0].toLowerCase()) {
back = back[0].toLowerCase() + back.slice(1)
front = front[0].toUpperCase() + front.slice(1)
}
// Don't double "y" in the suffix
if (trailingY.test(front) && leadingY.test(back)) {
back = back.slice(1)
}
return front + back
})
.join("")
}