Truncating Strings in JavaScript

JavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the concept of truncating strings in JavaScript. Truncating a string involves shortening the length of a given string up to a specified length. Through various exercises and examples, you will learn how to implement a function that truncates strings and appends ellipsis to the end of the truncated string.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.

Truncate a String in JavaScript

To truncate a string in JavaScript, you can use the truncateString function. This function takes two arguments: str (the string to be truncated) and num (the maximum length of the truncated string).

The truncateString function checks if the length of the str is greater than num. If it is, the function truncates the string to the desired length and appends '...' to the end. If not, it returns the original string.

Here's the code for the truncateString function:

const truncateString = (str, num) =>
  str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + "..." : str;

And here's an example of how to use the truncateString function:

truncateString("boomerang", 7); // 'boom...'

Summary

Congratulations! You have completed the Truncate String lab. You can practice more labs in LabEx to improve your skills.