I remember learning how to determine syllables by clapping my hands when I was in kindergarten. I remember chatting with the kids around me finding who had the same amount of syllables in their name as I did. I was a 2 (And-rew) so I was hanging with the Alex’s and the Ryan’s.

It was probably a few years after that that I learned what a Haiku was. A poem dictated by the syllables in each line: 5–7–5. I’m pretty sure most of us remember that, and I’m pretty sure most of us have thought of silly haikus by sounding out the syllables in our heads. But can an app programmatically count syllables with accuracy and in turn determine if a haiku is valid?

Yes. Yes it can.

Here is the code I used to count the syllables in a word:

function syllables(word) {

word = word.toLowerCase();

if(word.length <= 3) { return 1; }

return word.replace(/(?:[^laeiouy]es|ed|lle|[^laeiouy]e)$/, '')

.replace(/^y/, '')

.match(/[aeiouy]{1,2}/g).length;

}

Basically, if a word has 3 characters or less, there is one syllable. For words with more characters, you need to count the vowels. One syllable per vowel. There are exceptions to this rule however. Most notably, when words have ‘ed’ at the end of the word you don’t add an extra syllable in most cases.

I’ve found this solution to be reasonably accurate, but there are more exceptions to the rule that could be added to make this better. I just haven’t found those exceptions yet.

So using my syllables function I am able to validate a haiku like this:

function checkLine(sentence){

var count = 0;

var words = sentence.split(" ");



words.map(function(val, key){

count += syllables(val)

});



return count;



} function haiku(a, b, c){



if(!a || !b || !c){

return {result: false, error: "Invalid input. Call haiku(line1, line2, line3)"}

}



result = [checkLine(a), checkLine(b), checkLine(c)];

expected = [5, 7, 5];



if(arrayCompare(result, expected)){

return true;

}



return {result: false, syllables:result};

} function arrayCompare(a1, a2){

return a1.length==a2.length && a1.every(function(v,i) { return v === a2[i]})

}

You pass the haiku function three sentences as parameters and the function will return either ‘true’ if it is a valid haiku or it will return a result of ‘false’ and an array of the syllables per line.

This function could be made even better if you could optionally pass an expected syllables array, so your poetry didn’t always have to be 5–7–5.

But that’s javascript validating a haiku. Pretty exciting for me, the English Major / Programmer.

Have you worked with natural language programmatically before? Could this be solved better? Leave a comment!