jQuery text truncation (read more style)

Mazzi picture Mazzi · Feb 12, 2010 · Viewed 42.9k times · Source

My question is very similar to "Trim text to 340 chars" but in jQuery. It sounded very straight forward but when I searched around I couldn't find any reference for it.

Ok, I have a div $('#content') I want to trim the text to 'x' amount of characters lets say '600' BUT I don't want it to break the word it self! Like NOT 'The Ques...' BUT 'The Questions...'.

What happens to the rest of the text? Well, I hide it and will show it on request! But wait, it should first remove the '...' and show the text right after where it hid.

Here is the sample structure for $('#content'):

<div id="content">
    <p>Once upon a midnight dreary, while I pondered weak and weary,Over many a quaint and curious volume of forgotten lore.</p>
    <p>Writing example text is very boring.</p>
    <p>Specially when you are dumb enough not to copy and paste. Oh!</p>
    <p>Once it sheltered the rogues and rapscallions of the British Empire; now Kangaroo Island is ready and waiting for some derring-do of your own. Venture into the rugged wilds of the island, traversing untamed bushland and pristine beaches seeking out seal, penguin and sea lion colonies. Meet the land loving locals - koalas, goannas, echidnas and the island's own species of kangaroo. </p>
</div>

How it should load:

Once upon a midnight dreary, while I pondered weak and weary,Over many a quaint and curious volume of forgotten lore.

Writing example text is... [Read More]

After click on 'Read More':

Once upon a midnight dreary, while I pondered weak and weary,Over many a quaint and curious volume of forgotten lore.

Writing example text is very boring.

Specially when you are dumb enough not to copy and paste. Oh!

Once it sheltered the rogues and rapscallions of the British Empire; now Kangaroo Island is ready and waiting for some derring-do of your own. Venture into the rugged wilds of the island, traversing untamed bushland and pristine beaches seeking out seal, penguin and sea lion colonies. Meet the land loving locals - koalas, goannas, echidnas and the island's own species of kangaroo.


UPDATE: I have found these two plug-ins that do basically same job as this best answer. However the best answer has some functionalities that those plug-ins don't have and vice versa!

Answer

Tim R picture Tim R · Feb 12, 2010

The following works for limiting the amount of text if you don't mind losing the paragraph tags.

<script type="text/javascript">
var shortText = $("#content").text()    // get the text within the div
    .trim()    // remove leading and trailing spaces
    .substring(0, 600)    // get first 600 characters
    .split(" ") // separate characters into an array of words
    .slice(0, -1)    // remove the last full or partial word
    .join(" ") + "..."; // combine into a single string and append "..."
</script>