W3jar
321 words
2 minutes

How to Truncate a String in JavaScript

To truncate a string in JavaScript, you can use several methods depending on your specific needs. Here are some common approaches:

1. Using substring() Method#

The substring() method extracts characters from a string between two specified indices and returns a new substring.

let str = "Hello, world!";
let maxLength = 5;
let truncatedStr = str.substring(0, maxLength); // "Hello"

2. Using slice() Method#

The slice() method extracts a section of a string and returns it as a new string. It works similarly to substring() but can handle negative indices.

let str = "Hello, world!";
let maxLength = 5;
let truncatedStr = str.slice(0, maxLength); // "Hello"

3. Using substr() Method#

The substr() method extracts a substring from a string, starting at a specified position and extending for a given number of characters. Note that substr() is considered a legacy method and might be less preferred in modern code.

let str = "Hello, world!";
let maxLength = 5;
let truncatedStr = str.substr(0, maxLength); // "Hello"

4. Adding an Ellipsis#

If you want to truncate the string and add an ellipsis (”…”) to indicate that the text has been cut off, you can use the following approach:

function truncateWithEllipsis(str, maxLength) {
    if (str.length <= maxLength) {
        return str;
    }
    return str.slice(0, maxLength) + "...";
}

let str = "Hello, world!";
let maxLength = 5;
let truncatedStr = truncateWithEllipsis(str, maxLength); // "Hello..."

5. Handling Multiline Strings#

If you have a multiline string and want to truncate based on the number of characters, the above methods still apply. However, if you want to truncate based on the number of lines, you might need a custom function:

function truncateByLines(str, maxLines) {
    let lines = str.split("\n");
    if (lines.length <= maxLines) {
        return str;
    }
    return lines.slice(0, maxLines).join("\n") + "\n...";
}

let multilineStr = "Line 1\nLine 2\nLine 3\nLine 4";
let maxLines = 2;
let truncatedStr = truncateByLines(multilineStr, maxLines); // "Line 1\nLine 2\n..."

Choose the method that best fits your needs based on whether you want to handle simple truncation, add an ellipsis, or manage multiline text.