Truncate a String

Learn how to solve the freeCodeCamp algorithm 'Truncate a String' using a for-loop and the String.slice() method!

Truncate a String

In the freeCodeCamp algorithm we need to create a function that will accept 2 arguments, a string, and a number which denotes the max length of said string. If the string is longer than the max length we need to return a truncated version of the string with ... at the end.

Spec

  • truncateString("A-tisket a-tasket A green and yellow basket", 8) should return "A-tisket..."
  • truncateString("Peter Piper picked a peck of pickled peppers", 11) should return "Peter Piper..."
  • truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length) should return "A-tisket a-tasket A green and yellow basket"
  • truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2) should return "A-tisket a-tasket A green and yellow basket"
  • truncateString("A-", 1) should return "A..."
  • truncateString("Absolutely Longer", 2) should return "Ab..."

Real-World Use Cases

First off, what does it mean to truncate something?

trun·cate

/ˈtrəNGˌkāt/Submit
verb
shorten (something) by cutting off the top or the end.

You probably encounter truncated strings way more than you even realize. Lots of featured blog posts and articles on websites are truncated so that they don't show the entire post until the user clicks through to it.

codesnippet-truncate-a-string

Not to mention, Google's search results are truncated so that they only display a certain amount of characters. This keeps Google's search results nice and neat and consistent between all pages and results.

codesnippet-truncate-a-string-linkedin

Psuedocode

Let's break down the algorithm before we actually write any code:


// Create a function that will accept a string and a number
    
    // Check if string length is less than or equal to number
        // If so, return the str - no truncation needed
        
    // If string length is greater than number
        // Slice the string at index 0 and at the index of number
        // Append the ellipsis to the string
        // Return the string

Solving the Algorithm

Setting up the function

We can use the function boilerplate given to us from freeCodeCamp. This will give us our string, str, and num which is the number at which we need to truncate str:

function truncateString(str, num) {
  // Clear out that junk in your trunk
  return str;
}

truncateString("A-tisket a-tasket A green and yellow basket", 8);

Check if str length is less than or equal to num

If the length of str is less than or equal to num than no truncation is needed. We only need to truncate strings that have more characters than the value of num. We can also got rid of the return statement that we get from the initial boilerplate function as we will be adding our own in the next step.

function truncateString(str, num) {
  if(str.length <= num) {
		return str;
	}
}

truncateString("A-tisket a-tasket A green and yellow basket", 8);

Handle when length of str is greater than num

When the length of str is greater than num then we need to truncate, or essentially cut str at the index of num, and the append the ellipsis (...) to the end of str.

We can accomplish this by using the String.slice() method which will allow us to specify the index at which a string should be sliced and we can optionally specify the index at which the slice should end. In our case, we will take a slice of the string from the 0 index all the way to the specified num index. That would look something like this:

function truncateString(str, num) {

	if(str.length <= num) {
		return str;
	}

	if(str.length > num) {
		return str.slice(0, num) + "...";
	}
}
truncateString("A-tisket a-tasket A green and yellow basket", 8)
// truncateString("Peter Piper picked a peck of pickled peppers", 11)
// truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)
// truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)
// truncateString("A-", 1)
// truncateString("Absolutely Longer", 2)

Test this code in your browser console

As you can see, we end up returning the value of str, after we've String.slice'd it, and then appended the ... to the end.

Recap

We were able to solve the freeCodeCamp algorithm "Truncate a String" by breaking down the requirements of the algorithm and using a for-loop along with the String.slice() method. I hope you found this walkthrough to be helpful. I'd love to see your solutions or any other use-cases that you might have for this algorithm!

Shoot me an email at [email protected] with any questions and if you enjoyed this, stay tuned and subscribe below! 👇

Help us improve our content