November 07, 2009

Javascript String truncate function

Javascript String truncate function, This function helps us to truncate the given string to the particular given character length.

function truncate(text, length, ellipsis) {

// Set length and ellipsis to defaults if not defined
if (typeof length == 'undefined') var length = 100;
if (typeof ellipsis == 'undefined') var ellipsis = '...';

// Return if the text is already lower than the cutoff
if (text.length < length) return text;

// Otherwise, check if the last character is a space.
// If not, keep counting down from the last character
// until we find a character that is a space
for (var i = length-1; text.charAt(i) != ' '; i--) {
length--;
}

// The for() loop ends when it finds a space, and the length var
// has been updated so it doesn't cut in the middle of a word.
return text.substr(0, length) + ellipsis;
}

var some_text = 'This is example text This is example text This is example text This is example text This is example text ';

Call to the above function is,
truncate(some_text, 10);

Output,

This is ex...

2 comments:

  1. Wow, nice.. it,s helpful for any type of websites. I have added this to my bookmarks.I hope have such type of wonderful information using this blog.

    Pooja

    MLM Developers India

    http://mlmdevelopers.com/products/mlm-software/corporate-mlm-soft/feature.html

    ReplyDelete
  2. I am very like this posting, waitng for next..pls keep continue new posts.

    http://mlmdevelopers.com/products/mlm-software/corporate-mlm-software/feature.html

    ReplyDelete