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
.