How to Truncate a String in JavaScript

Updated onbyAlan Morel
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:

JAVASCRIPT
const string = "development"; console.log(string);
BASH
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:

JAVASCRIPT
const string = "development"; const truncated = string.slice(0, 3); console.log(truncated);
BASH
dev

Now we can add the ellipsis to the end of the string:

JAVASCRIPT
const string = "development"; const truncated = string.slice(0, 3) + "..."; console.log(truncated);
BASH
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:

JAVASCRIPT
const string = "development"; const truncated = string.length > 3 ? string.slice(0, 3) + "..." : string; console.log(truncated);
BASH
dev...

Finally, let's convert this into a reusable function:

JAVASCRIPT
const truncate = (string, length) => { return string.length > length ? string.slice(0, length) + "..." : string; }; const string = "development"; const truncated = truncate(string, 3); console.log(truncated);
BASH
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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.