How to make if a string up to 40 characters of the text hiding?

Good evening, everyone, and happy holidays!
I can tell you how to do, if a string up to 40 characters of the text hiding?
And when the text disappears, it is substituted for the ellipsis..

I thought slice would help, but I'm either not using it correctly or it is not suitable...

function myFunction(text) {
 text = prompt("", "");
 text = text.split(' ').join(");

 // text = text.slice(0, 50);
 if (text.length > 40) {
 text = text.slice(0, 40);
console.log(text.length);
 document.write(text + '... ');
 //return text;
 } else {
console.log(text.length);
return;
}
}
myFunction();


For earlier thanks!
March 20th 20 at 11:24
3 answers
March 20th 20 at 11:26
I remember I came across a similar problem learn.javascript.ru
sliceText function(str, maxlength) {
 return (str.length > maxlength) ?
 str.slice(0, maxlength - 3) + '...' : str;
}
March 20th 20 at 11:28
// t.length - (t.length - 40) -> t.length - t.length + 40 -> 40
t.substring(0, 40)+'...'
- Wilford_Roob commented on March 20th 20 at 11:31
March 20th 20 at 11:30
What is there to fence a lot of code. Cut, added and all.

const str = "I Can tell you how to do, if a string up to 40 characters of the text hiding?";

short function(str, len = 40) {
 if (str.trim().length <= len) return str.trim();

 return str.trim().substr(0, len - 3).trim() + "...";
}

short(str); // string to 40 characters, including dots
short(str, 80); // string to 80 characters, including dots


PS good would have to cut off the possible characters at end of line, dots, commas, dashes, and so on.

Find more questions by tags JavaScript