DEV Community

Cover image for A snippy JS function to trim those long strings
Brett Thurston
Brett Thurston

Posted on • Originally published at brettthurston.com

A snippy JS function to trim those long strings

In this article you'll find a method to use whenever you have a long string that may funk up your UI components.

I was working on a list item component for a project and found a problem we run into a lot. What I have is a list of cards that bring in a title, publish date, and an episode description. Instead of manually trimming the string in the component itself, what if we could trim the string on the fly? This is especially useful when working with JS frameworks like React JS and Vue.

Screen Shot 2021-02-05 at 9.27.07 AM

The description length of each episode will vary from each publication. I'm positive the descriptions will run past the limit I want them to in these card components. Then my list of cards will all have different heights. I like symmetry so I needed to trim these description strings on the fly. Here's how I did it and one of many different ways to do it.


function truncate(string, characterLimit) {
/* first argument, pass in a string */
/* optional second argument: pass in a character 
      limit for this string. */
/* reminder: ?? is a nullish coalescing operator. 
      if we find that the 2nd argument passed in is 
      null or undefined, we default the character limit 
      to 160 characters */
  let limit = characterLimit ?? 160;
/* set up a variable called finalString to return at the end.  */
  let finalString;
/* if condition that asks if the string character count is 
       greater than or equal to the limit variable. if it is then 
       we want to remove everything after the number of the 
       limit set and append ellipse ("...") */
  if (string.length >= limit) {
    finalString = string.substring(0, limit);
    finalString = finalString + "...";
  } else {
/* if the string is less than or equal to the limit, let's go 
       ahead and pass the string by assigning it to our 
       finalString variable */
    finalString = string;
  }
  return finalString;
}
Enter fullscreen mode Exit fullscreen mode

Let's see what happens when we use this method:

const shortDescription = "If a parsley farmer gets sued, can they garnish his wages?"

const longDescription = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ex ante, molestie eu nisl non, tempor rutrum tortor. Suspendisse ultricies odio ac turpis porta volutpat. Vestibulum rhoncus laoreet elit ut dictum. Ut id lorem ut ipsum cursus eleifend sed vitae dui. Mauris commodo elit at leo consectetur, ut blandit lacus laoreet. Vivamus placerat congue consectetur. Vivamus non nisi a tortor aliquet dictum. Sed ut condimentum nunc. In hac habitasse platea dictumst. Praesent id egestas libero. Vivamus sed tellus orci. Ut luctus mauris nunc, pulvinar bibendum urna dictum non. Duis bibendum commodo arcu, ut elementum diam vulputate vitae."

truncate(longDescription)
/* "Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Etiam ex ante, molestie eu nisl non, tempor rutrum tortor. 
Suspendisse ultricies odio ac turpis porta v..." */

truncate(longDescription, 250)
/* "Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
Etiam ex ante, molestie eu nisl non, tempor rutrum tortor. 
Suspendisse ultricies odio ac turpis porta volutpat. Vestibulum 
rhoncus laoreet elit ut dictum. Ut id lorem ut ipsum cursus 
eleifend s..." */

truncate(shortDescription)
/* "If a parsley farmer gets sued, can they garnish his wages?" */

shortDescription.length
/* 58
58 is less than the default 160 limit, so the string is passed 
through unmodified */
Enter fullscreen mode Exit fullscreen mode

So this function not only trims your long copy descriptions, but it also allows you to pass in a limit to override whatever default limit you set. This is super handy because now, you've written a function that becomes super nimble. For instance, I used the same truncate function in this fixed audio player bar I'm working on. Notice it's trimming the episode title.

Screen Shot 2021-02-05 at 10.02.55 AM

Whenever you're writing your functions make sure they have one responsibility, but allow for customization as needed.

So now you've got one way to trim a long description in the UI. You've seen how to write a function that considers future use in other areas of your program too.

How would you handle this equation? Share your solutions below.

Thanks for reading and happy snipping!

Photo by Les Triconautes on Unsplash

Top comments (1)

Collapse
 
mycodemagic profile image
My Code Magic

I like your cover pic very much match your title πŸ™ƒπŸ˜‰