Truncating Strings in JavaScript

JavaScriptJavaScriptBeginner
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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28671{{"`Truncating Strings in JavaScript`"}} javascript/data_types -.-> lab-28671{{"`Truncating Strings in JavaScript`"}} javascript/arith_ops -.-> lab-28671{{"`Truncating Strings in JavaScript`"}} javascript/comp_ops -.-> lab-28671{{"`Truncating Strings in JavaScript`"}} end

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.

Other JavaScript Tutorials you may like