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!
Create an RSS Reader in Node
Getting Started with Electron
Git Tutorial: Learn how to use Version Control
How to Serve Static Files with Nginx and Docker
How to build a Discord bot using TypeScript
Getting Started with Deno
How to deploy a MySQL Server using Docker
Getting Started with Handlebars.js
Getting User Location using JavaScript's Geolocation API
Getting Started with Moment.js
Getting Started with React
Getting Started with Vuex: Managing State in Vue
