Creative Communities of the World Forums

The peer to peer support community for media production professionals.

Activity Forums Adobe After Effects Expressions Breaking text lines evenly based on length

  • Breaking text lines evenly based on length

    Posted by TIneke Van Schalkwyk on August 27, 2020 at 7:59 pm

    I would like to break my headlines evenly into 1/2/3 lines depending on the length of the headline given. Standard text just wraps and can leave me with one word on the second or third line which doesn’t look good.

    Here is what we have so far which is working except that for some reason it is cutting off the last word of the text. Any ideas what needs to be fixed here:

    function breakTextInEqualParts(myString, partNo) {
    var splits = [0];
    var subStrings = [];
    var strLength = myString.length;
    if (
    partNo < 2 ||
    myString == "" ||
    text.sourceText.indexOf("\n") != -1 ||
    text.sourceText.indexOf("\r") != -1 ||
    text.sourceText.length < 20
    )
    return myString;

    for (var i = 1; i < partNo; i++) {
    splits.push(Math.round(strLength / partNo) + splits[i - 1]);
    }
    splits.push(strLength);

    for (var i = 0; i < strLength - 1; i++) {
    subStrings.push(breakText(myString, splits[i], splits[i + 1]));
    }

    return subStrings.join("\n");

    function breakText(myString, idx1, idx2) {
    if (myString == "") return "";
    idx1 = calcIndex(myString, idx1);
    idx2 = calcIndex(myString, idx2);
    return myString.substring(idx1, idx2);

    function calcIndex(myString, idx) {
    if (idx == 0) return idx;
    var before = myString.lastIndexOf(" ", idx);
    var after = myString.indexOf(" ", idx + 1);

    if (before == -1 || (after != -1 && idx - before >= after - idx)) {
    idx = after;
    } else {
    idx = before;
    }
    return idx;
    }
    }
    }

    var len = text.sourceText.length;
    if (len > 40) parts = 2;
    else if (len > 20) parts = 3;
    else parts = 1;

    var ctrlStyle = thisComp.layer(index - 1).text.sourceText.style;
    val = breakTextInEqualParts(text.sourceText, parts);

    TIneke Van Schalkwyk replied 5 years, 11 months ago 1 Member · 0 Replies
  • 0 Replies

Sorry, there were no replies found.

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