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 TypeScript
How to Install Node on Windows, macOS and Linux
Managing PHP Dependencies with Composer
Getting Started with Svelte
Create an RSS Reader in Node
How to deploy a Node app using Docker
How to Scrape the Web using Node.js and Puppeteer
Build a Real-Time Chat App with Node, Express, and Socket.io
Learn how to build a Slack Bot using Node.js
Creating a Twitter bot with Node.js
Setting Up Stylus CSS Preprocessor
Setting Up a Local Web Server using Node.js
