Exercise 12: Truncate String with Ellipsis
Problem Statement
Function `truncate(str, maxLength)` banao jo string ko truncate kare aur ellipsis add kare.
Example: truncate("Hello world", 8) => "Hello..."
Sample Output:
truncate("Hello world", 8) => "Hello..."
truncate("Short", 10) => "Short"Solution
const truncate = (str, maxLength) => {
const s = String(str ?? "");
if (s.length <= maxLength) return s;
return s.slice(0, maxLength - 3) + "...";
};Explanation
Overall Goal:
- String ko specified length tak truncate karna.
Real world:
- UI: long text truncation.
- Previews: content previews.