Drill

ProblemsJavaScript › text

Cut a description to length

mediumtextJavaScript

A listing card has room for a fixed number of characters, and a description cut mid-word looks broken.

truncateWords(text: string, limit: int) → string

Solve it in the editor →

Where you start

function truncateWords(text, limit) {
  
}

Worked examples

CallResult
truncateWords("The quick brown fox", 10)"The quick..."
truncateWords("Supercalifragilistic", 5)"Super..."
truncateWords("Short", 10)"Short"
truncateWords("a b c d e f", 5)"a b c..."

Hint

Look at the character sitting at `limit`: if it is a space, the slice is already clean and needs no trimming back.

Reference solution in JavaScript
function truncateWords(text, limit) {
  if (limit <= 0) return '';
  if (text.length <= limit) return text;
  let cut = text.slice(0, limit);
  if (text[limit] !== ' ') {
    const sp = cut.lastIndexOf(' ');
    if (sp > 0) cut = cut.slice(0, sp);
  }
  return cut.replace(/\s+$/, '') + '...';
}

The same problem in another language

More text problems in JavaScript