Categories
JavaScript Answers

How to truncate a string in JavaScript?

Spread the love

Sometimes, we want to truncate a string in JavaScript.

In this article, we’ll look at how to truncate a string in JavaScript.

How to truncate a string in JavaScript?

To truncate a string in JavaScript, we use the string substring method.

For instance, we write

const truncateString = (str, length) => {
  return str.length > length ? str.substring(0, length - 3) + "..." : str;
};

to define the truncateString function.

In it, we str.substring if str.length is bigger than length to return a truncated substring.

Otherwise, we return str.

Conclusion

To truncate a string in JavaScript, we use the string substring method.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.