Creative Communities of the World Forums

The peer to peer support community for media production professionals.

Activity Forums Adobe After Effects Expressions Сount the number of words in a text

  • Сount the number of words in a text

    Posted by Alex Andry on February 16, 2023 at 5:31 pm

    I have a task to count the number of words in a text. Here is an expression that works for this:

    txt=text.sourceText;

    varvalAry = txt.value.split(” “);

    var curLine = “”;

    for (var i=0;i<valAry.length;i++){

    curLine = i + ” ” +” “;}

    But if I add a space at the end of the text, then the expression considers the last space as a word.

    Please help me how to make a random space after the text not be considered as a word.

    Alex Andry replied 3 years, 5 months ago 3 Members · 5 Replies
  • 5 Replies
  • Dan Ebberts

    February 16, 2023 at 8:23 pm

    How about this:

    txt=text.sourceText.value;
    valAry = txt.replace(/\s+$/g,"").split(" ");
    valAry.length
  • Alex Andry

    February 17, 2023 at 6:53 am

    Thanks Dan, it works!

  • Alex Andry

    February 17, 2023 at 7:26 am

    Dan, can this expression be modified to make a text row calculation?

  • Filip Vandueren

    February 17, 2023 at 12:26 pm

    If you mean, count the number of lines broken off by hard and soft returns:

    txt = thisComp.layer("txt").text.sourceText;
    txt.split(/\r\n?|\n|\3/g).length

    If you need the number of lines that are being wrapped in a paragraph box, not by eneterd linebreaks: that’s harder.
    If all the paragraph-space-before and -after margins are at 0, and if the leading and fontsize is consistent across the whole text, and if all the lines are visible, and if you don’t care about empty lines at start or finish… (yes that’s a lot ifs) then it can (usually) be calculated by:

    txt = thisComp.layer("txt").text.sourceText;
    ld = txt.style.autoLeading ? txt.style.fontSize*1.2 : txt.style.leading;
    Math.round(thisComp.layer("txt").sourceRectAtTime().height/(ld));

    But this can break with fonts like Zapfino that may have extravagant Swashes that are much much larger than the font’s x-height.

  • Alex Andry

    February 17, 2023 at 1:05 pm

    Thanks a lot Philip, both expressions work great! I am grateful for your help and Dan’s help!

We use anonymous cookies to give you the best experience we can.
Our Privacy policy | GDPR Policy