Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Truncate with Ellipsis

Data Structures, Operators & Stringsmedium

Course · Section 9: Data Structures, Modern Operators and Strings · Lecture 128: Working With Strings - Part 1

Implement `truncate(s, n)` returning `s` unchanged if its length is at most `n`, otherwise the first `n` characters followed by three dots.

Sample tests

Input: truncate("hello world", 5)
Output: "hello..."
Input: truncate("hi", 5)
Output: "hi"

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Off-by-one on whether length equal to n should be truncated (it should not here).

Learning resources

  • MDN: String
Approach & explanation (try first)

Only strings longer than n are cut to n characters with an ellipsis appended.

Loading...
⌘/Ctrl + Enter

Run your code to see results.