How to Truncate a String in JavaScript
Truncating a string in JavaScript means cutting it down to a certain length and optionally adding an ellipsis or other ending. This guide covers multiple methods to achieve string truncation tailored for different scenarios.
Understanding string truncation
Truncation is the process of shortening a string by removing characters from the end until it reaches a specified length. Developers might truncate strings to maintain a clean UI where space is limited or to create previews of longer text.
Using the slice
method
The slice
method is the go-to for basic truncation without ending characters:
let str = "The quick brown fox jumps over the lazy dog"; let truncated = str.slice(0, 16); // "The quick brown f"
Adding an ellipsis with slice
To add an ellipsis or any other ending after truncation, concatenate it:
let truncated = str.slice(0, 16) + '...'; // "The quick brown f..."
Creating a truncate function
For reusability, define a function to truncate strings and append an optional ending:
function truncateString(str, length, ending = '...') { if (str.length > length) { return str.slice(0, length - ending.length) + ending; } return str; }
Using substring
for truncation
The substring
method is similar to slice
, but it does not accept negative indices:
let truncated = str.substring(0, 16); // "The quick brown f"
Handling edge cases
Always check the string's length to avoid unnecessary operations:
function safeTruncate(str, length, ending = '...') { if (str.length <= length) return str; return str.slice(0, length - ending.length) + ending; }
Using modern JavaScript features
Template literals and the ternary operator can make truncation more readable:
const truncateES6 = (str, length, ending = '...') => `${str.length > length ? str.slice(0, length - ending.length) + ending : str}`;
Truncating without cutting words
To avoid cutting words, use the lastIndexOf
method to find the last space within the limit:
function truncateAtLastSpace(str, length, ending = '...') { if (str.length <= length) return str; let trimmedString = str.slice(0, length + 1); return trimmedString.slice(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(' '))) + ending; }
Invite only
We're building the next generation of data visualization.
How to Remove Characters from a String in JavaScript
Jeremy Sarchet
How to Sort Strings in JavaScript
Max Musing
How to Remove Spaces from a String in JavaScript
Jeremy Sarchet
Detecting Prime Numbers in JavaScript
Robert Cooper
How to Parse Boolean Values in JavaScript
Max Musing
How to Remove a Substring from a String in JavaScript
Robert Cooper