Monthly Archives: June 2012

An elegant way to limit a text in javascript

This snippet will limit you’re text without cutting a word using jquery.

In this example, it will limit the title until the first occurrence of space starting from 10th position. This is somewhat the same approach using strpos() in php

$(document).ready(function(){
    var title = $.trim("   I am a very long title. Not really    ");
    var short_title = "";
    if (title.length > 10) {
       //indexOf will return the position of the first space starting from position 10
       short_title = title.substring(0, title.indexOf(" ",10)) + "...");
    }
});

Refer to MDN indexOf()