Text shortner function with js that end with ‘…’
You want a JavaScript function that shortens text and adds an ellipsis (“…”) to the end. Here’s a simple function that does that:
function shortenText(text, maxLength) {
if (text.length > maxLength) {
return text.substring(0, maxLength) + '...';
} else {
return text;
}
}
This function takes two arguments: the text to be shortened, and the maximum length you want the text to be. If the text is longer than the maximum length, it truncates the text and adds an ellipsis. If the text is already shorter than the maximum length, it returns the original text.
const title = "This is a very long title that needs to be shortened";
const shortenedTitle = shortenText(title, 20);
console.log(shortenedTitle); // Output: "This is a very long tit..."