Truncate String at Whitespace

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 a string at whitespace in JavaScript. We will learn how to limit the length of a string while preserving its readability by respecting whitespace. Through the implementation of String.prototype.slice() and String.prototype.lastIndexOf(), we will create a function that can truncate a string to a specified length with an optional ending.


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`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") subgraph Lab Skills javascript/variables -.-> lab-28670{{"`Truncate String at Whitespace`"}} javascript/data_types -.-> lab-28670{{"`Truncate String at Whitespace`"}} javascript/arith_ops -.-> lab-28670{{"`Truncate String at Whitespace`"}} javascript/comp_ops -.-> lab-28670{{"`Truncate String at Whitespace`"}} javascript/cond_stmts -.-> lab-28670{{"`Truncate String at Whitespace`"}} end

How to Truncate a String at Whitespace in JavaScript

To practice coding, open the Terminal/SSH and type node.

Here's a function that truncates a string up to a specified length while respecting whitespace whenever possible:

const truncateStringAtWhitespace = (str, lim, ending = "...") => {
  if (str.length <= lim) return str;
  const lastSpace = str.slice(0, lim - ending.length + 1).lastIndexOf(" ");
  return str.slice(0, lastSpace > 0 ? lastSpace : lim - ending.length) + ending;
};

To use this function, pass in the string you want to truncate as the first argument, the maximum length as the second argument, and an optional ending string as the third argument. If the length of the string is less than or equal to the specified limit, the original string will be returned. Otherwise, the function will find the last space before the limit and truncate the string at that point, adding the ending string if specified.

Here are some examples:

truncateStringAtWhitespace("short", 10); // 'short'
truncateStringAtWhitespace("not so short", 10); // 'not so...'
truncateStringAtWhitespace("trying a thing", 10); // 'trying...'
truncateStringAtWhitespace("javascripting", 10); // 'javascr...'

Summary

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

Other JavaScript Tutorials you may like