Horje
How to Truncate a String in JavaScript ?

In JavaScript, there are several ways to truncate a string which means cutting off a part of the string to limit its length. Truncating a string is useful when we want to display only a certain number of the characters in the user interfaces such as previewing a longer text or ensuring that text fits within the specified space.

Use the below methods to Truncate a String in JavaScript:

Using the substring() method

In this approach, we are using the substring() method to extract characters from the string between the two specified indices and return the new sub-string.

Example: Truncate a String in JavaScript using the substring() method.

JavaScript
function GFG(str, maxLength) {
    if (str.length > maxLength) {
        return str.substring(0, maxLength) + '...';
    }
    return str;
}
const longText = "GeeksforGeeks, Learning.";
const truncatedText = GFG(longText, 20);
console.log(truncatedText);

Output
GeeksforGeeks, Learn...

Using the slice() method

In this approach, we are using the slice() method that extracts a section of the string and returns it as a new string without the modifying the original string.

Example: Truncate a String in JavaScript using the slice() method.

JavaScript
function GFG(str, maxLength) {
    if (str.length > maxLength) {
        return str.slice(0, maxLength) + '...';
    }
    return str;
}

const longText = "GeeksforGeeks , Learning.";
const truncatedText = GFG(longText, 20);
console.log(truncatedText);

Output
GeeksforGeeks , Lear...

Using Regular Expression

In this approach, we use a regular expression to match the desired number of characters from the beginning of the string. This method can be particularly useful if you want to ensure that the truncation does not break words in the middle.

Example: Truncate a String in JavaScript using a regular expression.

JavaScript
function truncateString(str, maxLength) {
  if (str.length <= maxLength) {
    return str;
  }
  const regex = new RegExp(`^.{0,${maxLength}}`);
  const truncated = str.match(regex)[0];
  return truncated;
}

// Example usage
const str = "This is a long string that needs to be truncated.";
const maxLength = 20;
const result = truncateString(str, maxLength);
console.log(result); // Output: "This is a long stri"

Output
This is a long strin





Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Toggle Popup using JavaScript ? How to Toggle Popup using JavaScript ?
Median of 2 Sorted Arrays of Equal Size using JavaScript Median of 2 Sorted Arrays of Equal Size using JavaScript
How to use Interface with Class in TypeScript ? How to use Interface with Class in TypeScript ?
How to find the Total Number of Elements in an Array in TypeScript ? How to find the Total Number of Elements in an Array in TypeScript ?
How to Repeat a String in JavaScript ? How to Repeat a String in JavaScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14