JavaScript Truncate String: What You Need To Know

If you are working with JavaScript, you may encounter situations where you need to truncate a string to a certain length. For example, you may want to display a short summary of a blog post, or limit the number of characters in a user input. How can you do that in JavaScript?

In this ultimate guide, I will show you how to:

  • Truncate string at a certain length
  • Add ellipsis (…) when string is too long
  • Use JavaScript to shorten string to the closest word
  • Remove everything after the first capital letter in a string
  • Extract the date part from a string
  • Round a string to the nearest integer
  • Replace the middle part of a string with ellipsis (…)
  • Use slice() method to trim a string in JavaScript

By the end of this post, you will be able to truncate any string in JavaScript with ease.

JavaScript truncate string to length

One of the fundamental approaches to truncate a string in JavaScript is by specifying a maximum length. By using the JavaScript substring() method, you can effortlessly achieve this.Let’s truncate a string to a specific length using substring() method:
function truncateToLength(inputString, maxLength) {
  return inputString.length > maxLength 
    ? inputString.substring(0, maxLength) 
    : inputString;
}

// Example Usage:
const originalString = "JavaScript is fascinating!";
const truncatedString = truncateToLength(originalString, 11);
console.log(truncatedString);  
// Output: "JavaScript"
JavaScript substring() Method
JavaScript substring() Method

Truncate string with ellipsis (...)

Adding an ellipsis (...) at the end of a truncated string is a common design choice, especially when dealing with user interfaces. 

Let’s see how to truncate a string in JavaScript with ellipsis:

function truncateWithEllipsis(inputString, maxLength) {
  return inputString.length > maxLength
    ? inputString.substring(0, maxLength - 3) + "..."
    : inputString;
}

// Example Usage:
const originalString = "JavaScript is fascinating!";
const truncatedString = truncateWithEllipsis(originalString, 15);
console.log(truncatedString);
// Output: "JavaScript i..."

This function truncateWithEllipsis()truncates a given inputString to a maximum length specified by maxLength. If the string is longer than the maximum length, it shortens it by removing the last three characters and adds "..." to indicate truncation; otherwise, it returns the original string.

String truncate to nearest word

Ensuring that your truncated string ends at the nearest word boundary enhances readability. The lastIndexOf() array method can help in identifying the last space before the maximum length:

function truncateToNearestWord(inutString, maxLength) {
  if (inutString.length <= maxLength) return inutString;

  const lastSpaceIndex = inutString.lastIndexOf(" ", maxLength);
  return inutString.substring(0, lastSpaceIndex) + "...";
}

// Example Usage:
const originalString = "JavaScript is fascinating!";
const truncatedString = truncateToNearestWord(originalString, 10);
console.log(truncatedString);
// Output: "JavaScript..."

This JavaScript function truncateToNearestWord() truncates a given input string to a specified maximum length, ensuring that the truncation occurs at the end of a word to maintain readability. It cleverly finds the last space within the specified length and shortens the string to that point, appending ellipses for brevity.

Truncate a string after word

A possible way to make a string shorter and clearer is to cut it off after a certain word. Use the JavaScript indexOf() method to find the position of the word and truncate accordingly:

function truncateAfterWord(inputString, word) {
  const wordIndex = inputString.indexOf(word);
  return wordIndex !== -1
    ? inputString.substring(0, wordIndex + word.length) + "..."
    : inputString;
}

// Example Usage:
const originalString = "JavaScript offers versatility and performance!";
const truncatedString = truncateAfterWord(originalString, "versatility");
console.log(truncatedString);
// Output: "JavaScript offers versatility..."
This JavaScript function, truncateAfterWord(), shortens a given string by truncating it after the specified word, adding ellipses for a concise display.

Truncate a string to first capital letter

Sometimes, you may want to truncate a string to end at the first occurrence of a capital letter. This can be achieved by iterating through the characters and identifying the index:

function truncateToFirstCapital(inputString) {
  const capitalIndex = Array.from(inputString)
    .findIndex(char => char === char.toUpperCase());
    
  return (capitalIndex !== -1)
    ? inputString.substring(0, capitalIndex) + "..."
    : inputString;
}

// Example Usage:
const originalString = "javaScript is fascinating!";
const truncatedString = truncateToFirstCapital(originalString);
console.log(truncatedString);
// Output: "java..."
This function truncateToFirstCapital, cleverly shortens text by capturing it up to the first capital letter. It’s a valuable approach for summarizing information, empowering you to efficiently highlight key points concisely.

JavaScript truncate string to Date

In certain situations, you might want to truncate a string to include only the date portion. Here’s a simple example using the JavaScript split() method to extract the date from a string:

function truncateToDateString(inputString) {
  const datePortion = inputString.split(" ")[2];
  return datePortion;
}

// Example Usage:
const originalString = "Published on: 2023-12-24";
const truncatedDateString = truncateToDateString(originalString);
console.log(truncatedDateString);
// Output: "2023-12-24"
The truncateToDateString function efficiently isolates and retrieves the date portion from a given input string using the split() method.

JavaScript truncate string to whole number

In some scenarios, you might need to ensure that your truncated string always ends at a whole word or a specific index. Here’s an example using the JavaScript Math.floor() method to achieve this:

function truncateToWholeNumber(inputString, maxLength) {
  const wholeNumberIndex = Math.floor(maxLength / 10) * 10;
  return inputString.length > wholeNumberIndex 
    ? inputString.substring(0, wholeNumberIndex) + "..." 
    : inputString;
}

// Example Usage:
const originalString = "JavaScript is feature-rich and dynamic!";
const truncatedString = truncateToWholeNumber(originalString, 15);
console.log(truncatedString);  
// Output: "JavaScript..."

The truncateToWholeNumber() code efficiently shortens text to the nearest multiple of 10 within a specified length. It uses math to manage data well, which is very important for text processing.

JavaScript Floor() - Round Down a Number To Nearest Integer
Math.Floor() - JavaScript Round Down a Number To Nearest Integer

JavaScript truncate string dropdown

For user interfaces like dropdown menus, you may want to ensure that truncated strings fit within a specific width. Here’s an example of truncating a string for a dropdown:

function truncateForDropdown(inputString, maxWidth) {
  let truncatedString = inputString;
  while (truncatedString.length > maxWidth) {
    truncatedString = truncatedString.slice(0, -1);
  }

  return truncatedString;
}

// Example Usage:
const originalString = "JavaScript is dynamic and efficient!";
const truncatedDropdownString = truncateForDropdown(originalString, 10);
console.log(truncatedDropdownString);  
// Output: "JavaScript"
The truncateForDropdown() function efficiently shortens an input string to fit within a specified maximum width by iteratively removing characters until the width constraint is met. This algorithmic approach ensures optimal space utilization in dropdown menus.

Truncate middle of a string

In scenarios where you need to truncate the middle of a string, you can use a combination of the JavaScript substring() and slice() methods:

JavaScript substring() vs slice()
JavaScript substring() vs slice()
function truncateMiddle(inputString, maxLength) {
  if (inputString.length <= maxLength) return inputString;
  
  const midPoint = Math.floor(inputString.length / 2);
  const remainingLength = maxLength - 3; // Reserve space for "..."
  
  return inputString
    .substring(0, midPoint - remainingLength / 2) + "..." + 
    inputString.slice(midPoint + remainingLength / 2);
}

// Example Usage:
const originalString = "JavaScript is versatile and powerful!";
const truncatedString = truncateMiddle(originalString, 15);
console.log(truncatedString);  
// Output: "JavaScript i...and powerful!"
The truncateMiddle() function efficiently shortens an input string to a specified maximum length by removing a central portion, ensuring that the resulting string is within the defined limit. It calculates the midpoint and strategically preserves the essential segments on both sides, maintaining data integrity while accommodating space for the ellipsis ("...").

Truncate string using slice() method

Another powerful method for string truncation involves the JavaScript slice() method. It allows you to extract a portion of a string based on specified indices. 

JavaScript slice() Method
JavaScript slice() Method

Let’s see how you can truncate a string in JavaScript using slice():

function truncateUsingSlice(inputString, start, end) {
  return (inputString.length > end)
    ? inputString.slice(start, end) + "..."
    : inputString;
}

// Example Usage:
const originalString = "JavaScript is incredibly versatile!";
const truncatedString = truncateUsingSlice(originalString, 0, 10);
console.log(truncatedString);
// Output: "JavaScript..."
The truncateUsingSlice() function utilizes the slice() method to extract a portion of the input string defined by the specified start and end indices. This makes it easy to cut off a string and add “…” if the string is too long.

Conclusion

To truncate JavaScript strings effectively, you need to know the different methods and their advantages. Depending on your goals, you may want to use different approaches for UI design, data manipulation, or performance optimization. 

This ultimate guide has shown you some of the most common and useful ways to do that.

When you apply these methods to your own projects, think about what you want to achieve. Truncating strings is not just a technical skill; it’s a way to create better solutions for users.

What’s your go-to method for string truncation in JavaScript?

Scroll to Top