Categories
JavaScript Answers

How to Display Only 10 Characters of a Long String in JavaScript?

Spread the love

To display only 10 characters of a long string in JavaScript, we can use the slice method to return the first 10 characters of the string.

For instance, we can write:

const text = "I am too long string";  
const count = 10;  
const result = text.slice(0, count) + (text.length > count ? "..." : "");  
console.log(result)

We have the text string variable.

And then we have the count set to the max number of characters we want in the truncated string.

Next, we create the result truncated string by calling slice with 0 and the count .

And then we add '...' to the end of the string if text.length is bigger than count .

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.