2

I have a bunch of title texts that get generated they all have different .Length but at a specific startindex of the string I want to find the closest space and then remove the text after it and also the space, and then add "...".

The most important part is that it shouldnt extend 49 length

Example:

"What can UK learn from Spanish high speed rail when its crap"

I want to make sure that it becomes:

"What can UK learn from Spanish high speed rail..."

How can I do this with Jquery?

I have a C# code that acheive this:

public static string TrimLength(string text, int maxLength)
{
    if (text.Length > maxLength)
    {
        maxLength -= "...".Length;
        maxLength = text.Length < maxLength ? text.Length : maxLength;
        bool isLastSpace = text[maxLength] == ' ';
        string part = text.Substring(0, maxLength);
        if (isLastSpace)
            return part + "...";
        int lastSpaceIndexBeforeMax = part.LastIndexOf(' ');
        if (lastSpaceIndexBeforeMax == -1)
            return part + "...";
        else
            return text.Substring(0, lastSpaceIndexBeforeMax) + "...";
    }
    else
        return text;
}

But I have no idea how to do this with jquery

Any kind of help is appreciated or any kind of tips on how to achieve this.

Obsivus
  • 8,231
  • 13
  • 52
  • 97
  • 2
    `text-overflow: ellipsis` should do that. I am not sure why you want to code it. `if(text.length > 49) //do text-overflow: ellipsis`. – Mr_Green May 18 '13 at 10:56
  • 1
    @Mr_Green: `text-overflow` can't do character based trimming (assuming OP has to do this) and it only applies to text that doesn't fit into its box: http://jsfiddle.net/LtQ2j/3/ – Elle May 18 '13 at 11:22
  • There *is* the [jQuery ellipsis plugin](https://github.com/STAR-ZERO/jquery-ellipsis#name), if you want to answer the title literally, though, as others point, out, that's not what the question itself asks. – ruffin May 18 '13 at 12:53

3 Answers3

4

Here's a general Javascript solution to this common task. jQuery isn't necessary but is used for $.trim to keep the input string neat.

var ellipsis = "...";

function TrimLength(text, maxLength)
{
    text = $.trim(text);

    if (text.length > maxLength)
    {
        text = text.substring(0, maxLength - ellipsis.length)
        return text.substring(0, text.lastIndexOf(" ")) + ellipsis;
    }
    else
        return text;
}

And to test:

sentence = "The quick brown fox jumps over a lazy dog.";

for (var i = 10; i <= 50; i += 10){
    console.log(TrimLength(sentence, i));
};

Output:

The...
The quick brown...
The quick brown fox jumps...
The quick brown fox jumps over a...
The quick brown fox jumps over a lazy dog. 

> jsFiddle demo

It is also worth noting that you can achieve a similar effect with CSS's text-overflow, which may be better suited to your situation: http://jsfiddle.net/LtQ2j/3/

Elle
  • 3,695
  • 1
  • 17
  • 31
2

0, I guess you misunderstood the purpose of jQuery (just read the first paragraph: "What is jQuery?"). jQuery is a framework built on top of javascript to manipulate the DOM in the browser. For what you need you only need a simple javascript expression:

function trimToLen(str, maxLen) {
    var trimmed = str.substr(0, maxLen);
    return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…';
}

to make it work for strings shorter than the maxLex you have to add an additional condition:

function trimToLen(str, maxLen) {
    if (str.length <= maxLen) {
        return str;
    }
    var trimmed = str.substr(0, maxLen);
    return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…';
}

and now the examples:

trimToLen("too short", 15);
// returns: too short
trimToLen("equal to maxLen", 15);
// returns: equal to maxLen
trimToLen("a little more than maxLen", 15);
// returns: a little more…

Notice that I used (elipsis) instead of ... (3 x dot). Visually it is is pretty much the same but you save a couple of characters and also avoid complicating the logic with the length of the trimmed text (because you have 3 instead of 1 character).

Another thing you might want is to normalise spaces in order to catch tabs, new lines or spaces. This could be the case when you want to display a longer description (containing formatted text) in one short <a> or <span> tag. For that you can use a simple regex as the first expression in the function:

str = str.replace(/\s/g, ' ');
Gabriel Petrovay
  • 20,476
  • 22
  • 97
  • 168
0

Just for completeness, you can do slightly better using the 2-arg form of lastIndexOf:

var ellipsis = "...";

function Truncate(text, maxLength)
{
    if (text.length <= maxLength)
        return text;

    maxLength -= ellipsis.length;
    var space = text.lastIndexOf(" ", maxLength);
    if (space >= 0)
        maxLength = space;

    return text.slice(0, maxLength) + ellipsis;
}
Neil
  • 54,642
  • 8
  • 60
  • 72