Trimming Text with Length Constraints in JavaScript

1 min read .

When managing text in web applications, it’s often necessary to display shorter text snippets than the original text to maintain a clean and readable layout. We’ll create a JavaScript function that trims text to a specified length and adds an ellipsis ("…") if the text exceeds that length.

limitText Function

The limitText function is designed to trim text to a specified length and add an ellipsis if the text is longer than the given limit. Here is the function implementation:

function limitText(text, limit) {
    if (text) {
        return text.slice(0, limit) + (text.length > limit ? "..." : "");
    }
}

Code Explanation

  1. Empty Text Check:

    if (text) {
        // ...
    }
    • The function starts by checking if the text variable is not empty or null. This prevents errors that might occur if text is not provided or is null.
  2. Text Trimming:

    text.slice(0, limit)
    • slice(0, limit) is used to trim the text to the limit length. The slice method returns a substring from the start position (0) to the end position (limit).
  3. Adding Ellipsis:

    + (text.length > limit ? "..." : "")
    • If the text length is greater than the specified limit, an ellipsis ("…") is added to the end of the substring. If not, no additional characters are appended.

Example Usage

Let’s see how this function works with some examples:

console.log(limitText("Hello, world! This is a test.", 10));
// Output: "Hello, wor..."

console.log(limitText("Short text.", 20));
// Output: "Short text."
  • Example 1: "Hello, world! This is a test." is trimmed to 10 characters resulting in "Hello, wor..." because the original text exceeds the length limit.

  • Example 2: "Short text." is shorter than 20 characters, so the result is the original text without changes.

Use Cases

The limitText function is useful in various scenarios, such as:

  • Article Descriptions: Displaying a brief snippet of a long description.
  • Links: Trimming long link texts to keep the layout clean.
  • Widgets and UI: Limiting text length in UI elements such as cards and panels.

Conclusion

The limitText function is a simple yet effective tool for managing and displaying text snippets in your web applications. By trimming text to the specified length and adding an ellipsis if necessary, you can enhance user experience by maintaining a neat and readable layout. Be sure to adjust the length limit and format according to your application’s design and functionality needs.

See Also

chevron-up