5

I have a div which contains text (a string of length S) of an arbitrary length, but a fixed size. Beyond a certain length (let's call it L), the text is truncated and the remainder of the text is no longer visible. (Technically speaking, the range [0,L) is visible, the range [L,S) is not).

What I want to do is find the length L for the text by counting only the visible number of characters in the div. Any characters beyond the cut-off point should be disregarded.

I'm happy to use 3rd party libraries like jQuery etc if that will get the job done!

Jonathan Ellis
  • 5,221
  • 2
  • 36
  • 53

1 Answers1

2

Here is a function I made for trimming text:

function getTextThatFits(txt, w, fSize, fName, fWeight) {
    if (fWeight === undefined)
        fWeight = "normal";

    var auxDiv = $("<div>").addClass("auxdiv").css ({
        fontFamily : fName,
        fontSize : parseInt(fSize) + "px",
        position: "absolute",
        height: "auto",
        marginLeft : "-1000px",
        marginTop : "-1000px",
        fontWeight: fWeight,
        width: "auto"
    })
    .appendTo($("body"))
    .html(txt);

    var ww = (auxDiv.width() + 1);
    var str = txt;

    if (ww > w)
    {
        var i = 1, p = 1, u = txt.length, sol = 0;

        while (p <= u)
        {
            i = (p + u) >> 1;
            str = txt.slice(0, i);
            auxDiv.html(str);
            ww = (auxDiv.width() + 1);
            if (ww <= w) {
                sol = i;
                p = i + 1;
            }
            else u = i - 1;
        }

        str = txt.slice(0, sol);
    }
    $(".auxdiv").remove();
    auxDiv.remove();
    return str.length;
}

I'm using binary search for finding the text that fits into a specific width. In order to use the function, you must call it like this:

getTextThatFits(yourText, divWidth, fontSize, fontName, fontWeight=optional)
gabitzish
  • 9,535
  • 7
  • 44
  • 65
  • This looks like a fantastic answer. However, I'd really appreciate it if you could provide a slightly tweaked version for me. What I really need to do is not just get the text that fits (although this code is great!) is find the index of the string at which point the truncation occurs. The issue is that this Javascript is actually going to be running inside a web view in an iOS app and I need to get the index so that it can be matched up against the original string. – Jonathan Ellis Apr 11 '12 at 10:54
  • The posted function was modified so it returns the length of the string that fits, not the string itself. That means it return the index of the string at which point the truncation occurs. Or am i missing something? ... – gabitzish Apr 11 '12 at 11:02
  • Perfect! Thanks. Will give it a spin and see how it goes. – Jonathan Ellis Apr 11 '12 at 11:10