Given a string and a maximum length, truncate the string to the specified length and append "..." if the original string was longer. If the string is already shorter than or equal to the max length, return it unchanged. If maxLength is less than 3, return the first maxLength characters without ellipsis.

Examples:

Input: text = "Hello World", maxLength = 8 Output: "Hello..." Explanation: The string exceeds 8 characters, so truncate to 5 characters and add "..." Input: text = "Hi", maxLength = 10 Output: "Hi" Explanation: The string is already shorter than the max length, return as-is Input: text = "Test", maxLength = 2 Output: "Te" Explanation: maxLength is less than 3, return first 2 characters without ellipsis
Apex Code Editor

Welcome to Lightning Challenge!

Create an Account

Sign up to track your progress, earn points, and compete with others. Your solutions will be saved automatically.

Create account

How It Works

  • • Write your solution in the code editor
  • • Connect your Salesforce org to test
  • • Submit to check if your solution passes
  • • Use hints if you get stuck

Note

You can test your code by connecting to Salesforce, but to save your progress and earn points, you'll need to create an account. Your solutions and achievements will be tracked automatically once you're logged in.