Truncate a string

Truncate a String

Truncating a string means to shorten it by removing some of its characters. This is useful when you want to display only a portion of a long string or when you need to limit the length of input from a user.

Using substring() method:

The easiest way to truncate a string is to use the substring() method. This method takes two arguments: the starting index and the ending index (exclusive) of the part of the string you want to keep. Here's an example:


const str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
const truncated = str.substring(0, 20);
console.log(truncated); // Output: "Lorem ipsum dolor sit"

In this example, we're taking the first 20 characters of the string str and storing it in the variable truncated.

Using slice() method:

The slice() method also allows you to truncate a string. It takes two arguments: the starting index and the ending index (exclusive) of the part of the string you want to keep. Here's an example:


const str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
const truncated = str.slice(0, 20);
console.log(truncated); // Output: "Lorem ipsum dolor sit"

This example is similar to the previous one, but we're using the slice() method instead.

Using substr() method:

The substr() method works slightly differently than the previous two methods. It takes two arguments: the starting index and the number of characters to keep. Here's an example:


const str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
const truncated = str.substr(0, 20);
console.log(truncated); // Output: "Lorem ipsum dolor si"

In this example, we're taking the first 20 characters of the string str and storing it in the variable truncated. Note that the ending index is not exclusive in this case.

Using CSS:

You can also use CSS to truncate a string if you're displaying it on a webpage. The text-overflow: ellipsis; property can be used to add an ellipsis at the end of a truncated string. Here's an example:


.truncated {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 200px; /* adjust to fit your needs */
}

In this example, we're using the .truncated class to apply the truncation styles to an HTML element. The white-space: nowrap; property ensures that the text is not wrapped to the next line, while the overflow: hidden; property hides any text that doesn't fit within the specified width. The text-overflow: ellipsis; property adds an ellipsis at the end of the truncated text.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe