How to Truncate a String in JavaScript
Table of Contents
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:
JAVASCRIPTconst string = "development";
console.log(string);
BASHdevelopment
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:
JAVASCRIPTconst string = "development";
const truncated = string.slice(0, 3);
console.log(truncated);
BASHdev
Now we can add the ellipsis to the end of the string:
JAVASCRIPTconst string = "development";
const truncated = string.slice(0, 3) + "...";
console.log(truncated);
BASHdev...
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:
JAVASCRIPTconst string = "development";
const truncated = string.length > 3 ? string.slice(0, 3) + "..." : string;
console.log(truncated);
BASHdev...
Finally, let's convert this into a reusable function:
JAVASCRIPTconst truncate = (string, length) => {
return string.length > length ? string.slice(0, length) + "..." : string;
};
const string = "development";
const truncated = truncate(string, 3);
console.log(truncated);
BASHdev...
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!
- Getting Started with Express
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Using Axios to Pull Data from a REST API
- Getting Started with Moon.js