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.

Javascript
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.

Similar Reads

Approach 1: Using String Manipulation

...

Approach 2: Using substring()

In this approach, we are using String.slice() method To truncate a string and add ellipsis using String.slice(), check if the string length exceeds a limit, then use slice to extract characters and append ‘…’ for truncation....

Approach 3: Using Template Literals and Conditional Operator

In this approach we are using substring() method to truncate a string. If the input string surpasses the specified limit, it extracts the first characters and appends ‘…’ to indicate truncation....

Approach 4: Using Array.prototype.join()

In this approach, template literal and conditional (ternary) operator. If the length exceeds a limit, truncate and add ‘…’; otherwise, return the original string....