Truncate a String only on a word break with JavaScript

Truncate a String only on a word break with JavaScript

You can view this on Github or CodePen, info is at the bottom of the post. 

I’ve been finding myself needing to truncate strings more and more lately, especially while working with Twitter. I created a function that was simple and reusable. That is the point of Object Orientated Programming after all and sharing is caring – so here it is:

function truncateString(str, len, append)
{
   var newLength;
   append = append || "";  //Optional: append a string to str after truncating. Defaults to an empty string if no value is given
   
   if (append.length > 0)
    {
      append = " "+append;  //Add a space to the beginning of the appended text
    }
   if (str.indexOf(' ')+append.length > len)
   {
       return str;   //if the first word + the appended text is too long, the function returns the original String
   }
   
   str.length+append.length > len ? newLength = len-append.length : newLength = str.length; // if the length of original string and the appended string is greater than the max length, we need to truncate, otherwise, use the original string
   
        var tempString = str.substring(0, newLength);  //cut the string at the new length
        tempString = tempString.replace(/\s+\S*$/, ""); //find the last space that appears before the substringed text

   
   if (append.length > 0)
      {
           tempString = tempString + append;
      }

   return tempString;
};

In case you need some explanation

append = append || "";

This is just a way to set append to either what was passed in with the function call OR to a blank string “” if nothing was passed into the function. This is an easy way to make a parameter optional, although seems to be a bit controversial, but when it comes to programming, what techniques are ever agreed on? For completeness, here’s a few different ways to make a parameter optional:

function truncateString(str, len, append)
{
   if (append === undefined)
   { 
      //append isn't defined, so we can't use it
      //...
   }
   else
   {
      //append IS defined, so we can use it
      //...
   }

   //...
};

or if you are using ES6, you can do something like this:

function truncateString(str, len, append = "")
{
   //now append has a default value, but will be overridden if a parameter is placed in the function call
};

Ok, this could be an entire post all for itself… Moving on!

if (append.length > 0)
    {
      append = " "+append;  //Add a space to the beginning of the appended text
    }

Add a space to the beginning of your appended text, if any appended text exists, so your words don’t run together.

if (str.indexOf(' ')+append.length > len)
   {
       return str;   //if the first word + the appended text is too long, the function returns the original String
   }

If the first word, plus your appended text (if there is any) is going to be longer than your max length, the function simply returns the original string.

str.length+append.length > len ? newLength = len-append.length : newLength = str.length; // if the length of original string and the appended string is greater than the max length, we need to truncate, otherwise, use the original string

Here’s what it would look like as an if-else, in case you aren’t familiar with the conditional operator:

if (str.length+append.length > len)
{
   newLength = len-append.length;
}
else
{
   newLength = str.length; 
}

If the length of the original string plus the appended string is greater than the max length, then we need to truncate the original string to make room, otherwise, append can be appended without modifying the original string.

var tempString = str.substring(0, newLength);  //cut the string at the new length
tempString = tempString.replace(/\s+\S*$/, ""); //find the last space that appears before the substringed text

The first line var tempString = str.substring(0, newLength); creates a new string that is cut to the value of newLength, then tempString = tempString.replace(/\s+\S*$/, ""); takes the new, slimmed down string and finds the last instance of a space and removes whatever is left after that space. For example, if str was, “Cut this string down!” and tempString ended up being, “Cut this stri”, after calling tempString = tempString.replace(/\s+\S*$/, ""); tempString would become, “Cut this”.

if (append.length > 0)
{
   tempString = tempString + append;
}

Since we subtracted extra room for the appended string, it is added to the tempString if it isn’t blank.

return tempString;

Finally, return the new truncated String with or without appended text.

This code is also available on Github:

or as a CodePen:

See the Pen Truncate String at Last Space by Nate Follmer (@nfollmer) on CodePen.0

Leave a Reply