Current

I’ve re-worked this syllable counter script to:

  • Get the value of textarea 1.
  • Count the number of syllables in textarea 1.
  • Display the results in textarea 2.
  • Update the count every time the value of textarea 1 is edited.
  • Act as a function (be able to run in multiple instances if wanted).

Example function of current code

Input (Textarea 1)

i would appreciate
any help
at all

Results (Textarea 2)

11

Current code

Here is the existing code as a JSFiddle.


Goal

I would like this script to:

  • Count the syllables of textarea 1 on a per line basis: presumably by splitting the textarea 1 value where there are line breaks e.g. .split('\n');.
  • Output the results, showing the total number of syllables counted per line.

Example function of desired code

Input (Textarea 1)

i would appreciate
any help
at all

Results (Textarea 2)

6
3
2

Problem

I’m quite stuck as to how to do this and would really appreciate any help or JSFiddle showing how to work with the existing code to achieve this.


Notes

For anyone who may be interested using in the syllable count function code itself: it’s not 100% accurate and fails on some words but gives a good general idea.

有帮助吗?

解决方案

Try this and let me know if it's what you needed.

Callouts:

I created an array that spits the lines up stores them var arrayOfLines = $("[name=set_" + $input + "]").val().match(/[^\r\n]+/g);.

Then loop through that array and do exactly what you did before, but on each array entry. Then store the results in tempArr, and display the tempArr results.

See Fiddle

function $count_how_many_syllables($input) {
    $("[name=set_" + $input + "]").keyup(function () {

    var arrayOfLines = $("[name=set_" + $input + "]").val().match(/[^\r\n]+/g);
    var tempArr = [];
    var $content;
    var word;
    var $syllable_count;
    var $result;

    for(var i = 0; i < arrayOfLines.length; i++){
        $content = arrayOfLines[i];
        word = $content;
        word = word.toLowerCase();
        if (word.length <= 3) {
            word = 1;
        }
        if (word.length === 0) {
           return 0;
        }
        word = word.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '')
            .replace(/^y/, '')
            .match(/[aeiouy]{1,2}/g).length;
        $syllable_count = word;
        $result = $syllable_count;
        tempArr.push($result);
    }

    $("[name=set_" + $input + "_syllable_count]").val(tempArr);

    });
}

(function($) {
    $count_how_many_syllables("a");
})(jQuery);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top