How to useTemplate Literals and Conditional Operator in Javascript
In this approach, template literal and conditional (ternary) operator. If the length exceeds a limit, truncate and add ‘…’; otherwise, return the original string.
Syntax:
`string text ${expression} string text`
Example: In this example we are using the above-explained approach.
function truncateString(str, maxLength) {
return str.length > maxLength ?
`${str.slice(0, maxLength - 3)}...` : str;
}
let inputString = 'This is a Geeks for geeks article';
let truncatedString = truncateString(inputString, 30);
console.log(truncatedString);
Output
This is a Geeks for geeks a...
JavaScript Program to Truncate a String to a Certain Length and Add Ellipsis (…)
In this article, we will see how to truncate a string to a certain length and add an ellipsis (…) in JavaScript. To truncate a string to a specific length and add an ellipsis (…) in JavaScript means shortening the string to a predefined character count, indicating that the content continues beyond the truncated portion.
There are several methods that can be used to truncate a string to a certain length and add ellipsis (…) in JavaScript, which are listed below:
Table of Content
- Using String Manipulation:
- Using substring()
- Using Template Literals and Conditional Operator
We will explore all the above methods along with their basic implementation with the help of examples.