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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *