Truncate string and append dots using Javascript

How to truncate a string and append 3 dots in JavaScript.

function add3Dots(string, limit)
{
  var dots = "...";
  if(string.length > limit)
  {
    // you can also use substr instead of substring
    string = string.substring(0,limit) + dots;
  }

    return string;
}

Call like this

add3Dots("Hello World",9);

The above function call returns this string

Hello Wor...

 

A minified version of the above function is given here

function add3Dots(string, limit)
{
   return string = string.length > limit ? string.substring(0,limit) + "...": string;
}

A über minified version (with the price of readability) is given here


function aD(s,l){return s=s.length>l?s.substring(0,l)+"...":s;}

In this case you need to call like this…


aD("Hello World",9);
This entry was posted in JavaScript and tagged , , . Bookmark the permalink.

2 Responses to Truncate string and append dots using Javascript

  1. lucky says:

    getTruncatedString: function(originalString,length){
    var truncatedString = originalString.substring(0,length);
    if(truncatedString.length==length){
    return truncatedString= truncatedString+”….”;
    }
    return truncatedString;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>