0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Truncate String with Example

Use str.length to check string length and str.slice(0, maxLength) to truncate it; for example, function truncate(str, maxLength) { return str.length > maxLength ? str.slice(0, maxLength) + '...' : str; } truncates and adds ellipsis.
📋

Examples

Input"Hello, world!", 5
Output"Hello..."
Input"JavaScript", 10
Output"JavaScript"
Input"Hi", 0
Output"..."
🧠

How to Think About It

To truncate a string, first check if its length is greater than the maximum allowed length. If yes, cut the string from the start up to that length and add '...' to show it is shortened. If not, return the string as is.
📐

Algorithm

1
Get the input string and maximum length.
2
Check if the string length is greater than the maximum length.
3
If yes, cut the string from the start to the maximum length and add '...'.
4
If no, return the original string.
5
Return the resulting string.
💻

Code

javascript
function truncate(str, maxLength) {
  if (str.length > maxLength) {
    return str.slice(0, maxLength) + '...';
  } else {
    return str;
  }
}

console.log(truncate("Hello, world!", 5));
console.log(truncate("JavaScript", 10));
console.log(truncate("Hi", 0));
Output
Hello... JavaScript ...
🔍

Dry Run

Let's trace the input "Hello, world!" with maxLength 5 through the code.

1

Check string length

"Hello, world!" length is 13, which is greater than 5.

2

Truncate string

Take first 5 characters: "Hello".

3

Add ellipsis

Add '...' to get "Hello...".

4

Return result

Return "Hello...".

StepString LengthCondition (length > maxLength)Result
113trueTruncate and add '...'
2--"Hello..."
💡

Why This Works

Step 1: Check length

We use str.length to see if the string is longer than the allowed length.

Step 2: Cut string

If it is longer, str.slice(0, maxLength) extracts the first part up to the limit.

Step 3: Add ellipsis

Adding '...' shows the string is shortened for clarity.

🔄

Alternative Approaches

Using substring()
javascript
function truncate(str, maxLength) {
  return str.length > maxLength ? str.substring(0, maxLength) + '...' : str;
}
console.log(truncate("Hello, world!", 5));
Works similarly but <code>substring</code> is slightly older; both are fine for truncation.
Using ternary operator inline
javascript
const truncate = (str, maxLength) => str.length > maxLength ? str.slice(0, maxLength) + '...' : str;
console.log(truncate("Hello, world!", 5));
Shorter syntax using arrow function and ternary operator for concise code.
Truncate without ellipsis
javascript
function truncate(str, maxLength) {
  return str.length > maxLength ? str.slice(0, maxLength) : str;
}
console.log(truncate("Hello, world!", 5));
Simply cuts the string without adding '...', useful if no indication of truncation is needed.

Complexity: O(n) time, O(n) space

Time Complexity

The operation depends on slicing the string which takes O(n) time where n is the maxLength or string length.

Space Complexity

A new string is created when slicing, so space is O(n) proportional to the truncated length.

Which Approach is Fastest?

Using slice or substring are similar in speed; arrow functions add readability but no speed difference.

ApproachTimeSpaceBest For
slice()O(n)O(n)Common truncation with ellipsis
substring()O(n)O(n)Similar to slice, older syntax
Arrow function with ternaryO(n)O(n)Concise modern syntax
Truncate without ellipsisO(n)O(n)When no indication of truncation needed
💡
Always check if the string length exceeds the limit before truncating to avoid unnecessary changes.
⚠️
Forgetting to check string length first can cause cutting strings that are already short, adding unwanted ellipsis.