How to compute number of syllables in a word in javascript?

前端 未结 4 1472
执念已碎
执念已碎 2020-12-28 18:55

Is there javascript library for counting number of syllables in a word? How to count?

Thanks

Edit

Thank Sydenam and zozo for useful

4条回答
  •  独厮守ぢ
    2020-12-28 19:37

    I can see this is an old post but I stumbled across this function and found good use for it.

    One thing that I would like to add that will increase the accuracy of the syllable account - (to my knowledge).

    I noticed that the string "changes" shows as only being 1 syllable.

    I removed es from (?:[^laeiouy]es|ed|[^laeiouy]e)$ so that it's now ?:[^laeiouy]|ed|[^laeiouy]e)$.

    This seems to add the extra syllable count for words ending in "es". Also, to simplify things I put the array of matched words into a separate variable, this way you can check if any syllables are counted before giving any output:

    var count = function(word) 
    {
        word = word.toLowerCase();                                     
        word = word.replace(/(?:[^laeiouy]|ed|[^laeiouy]e)$/, '');   
        word = word.replace(/^y/, '');                                 
        //return word.match(/[aeiouy]{1,2}/g).length;   
        var syl = word.match(/[aeiouy]{1,2}/g);
        console.log(syl);
        if(syl)
        {
            //console.log(syl);
            return syl.length;
        }
    }
    

    I found this to be more convenient than necessary. If you have the function running in event listener that might fire before there are any words to check, this would be useful and prevent any errors such as Cannot read property 'length' of null.

    I just wanted to share my findings with anyone else who might find this and decide to use it.

提交回复
热议问题