How to Truncate a String in JavaScript

When you're working with strings from an external source, like user input or over the network, you usually don't have control over how long the string is.
That means that you need to make sure that the string is not too long before you use it, depending on the context.
When this happens, you might want to truncate the string to the desired length, with an ellipsis (...) at the end.
In this post, we'll learn how to truncate a string in JavaScript.
How to truncate a string in JavaScript
First let's start off with the string we want to truncate:
const string = "development";
console.log(string);
development
Let's say we want to truncate this to only the first 3
characters.
The first step here is to use the slice()
method to get the first 3 characters:
const string = "development";
const truncated = string.slice(0, 3);
console.log(truncated);
dev
Now we can add the ellipsis to the end of the string:
const string = "development";
const truncated = string.slice(0, 3) + "...";
console.log(truncated);
dev...
Now this works, however we want to make sure that we don't slice the string if it's already shorter than the desired length.
For that we can add a simple length check:
const string = "development";
const truncated = string.length > 3 ? string.slice(0, 3) + "..." : string;
console.log(truncated);
dev...
Finally, let's convert this into a reusable function:
const truncate = (string, length) => {
return string.length > length ? string.slice(0, length) + "..." : string;
};
const string = "development";
const truncated = truncate(string, 3);
console.log(truncated);
dev...
Now truncating a string is as easy as calling the truncate()
function and passing in the string and the desired length.
Conclusion
In this post, we learned how to truncate a string in JavaScript.
Simply use the slice()
method to get the desired length of the string if it's longer than the desired length, and add an ellipsis to the end.
Then you can convert this into a reusable function and use it whenever you need to truncate a string.
Thanks for reading!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!