Skip to main content

--description--

Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a ... ending.

--hints--

truncateString("A-tisket a-tasket A green and yellow basket", 8) should return the string A-tisket....

assert(
truncateString('A-tisket a-tasket A green and yellow basket', 8) ===
'A-tisket...'
);

truncateString("Peter Piper picked a peck of pickled peppers", 11) should return the string Peter Piper....

assert(
truncateString('Peter Piper picked a peck of pickled peppers', 11) ===
'Peter Piper...'
);

truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length) should return the string A-tisket a-tasket A green and yellow basket.

assert(
truncateString(
'A-tisket a-tasket A green and yellow basket',
'A-tisket a-tasket A green and yellow basket'.length
) === 'A-tisket a-tasket A green and yellow basket'
);

truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2) should return the string A-tisket a-tasket A green and yellow basket.

assert(
truncateString(
'A-tisket a-tasket A green and yellow basket',
'A-tisket a-tasket A green and yellow basket'.length + 2
) === 'A-tisket a-tasket A green and yellow basket'
);

truncateString("A-", 1) should return the string A....

assert(truncateString('A-', 1) === 'A...');

truncateString("Absolutely Longer", 2) should return the string Ab....

assert(truncateString('Absolutely Longer', 2) === 'Ab...');

--seed--

--seed-contents--

function truncateString(str, num) {
return str;
}

truncateString("A-tisket a-tasket A green and yellow basket", 8);

--solutions--

function truncateString(str, num) {
if (num >= str.length) {
return str;
}

return str.slice(0, num) + '...';
}

truncateString("A-tisket a-tasket A green and yellow basket", 8);