Back to Freecodecamp

Implement the Truncate a String Algorithm

curriculum/challenges/english/blocks/lab-truncate-string/ac6993d51946422351508a41.md

latest2.4 KB
Original Source

--description--

In this lab, you will practice truncating a string to a certain length.

Objective: Fulfill the user stories below and get all the tests to pass to complete the lab.

User Stories:

  1. You should have a function truncateString that accepts two arguments, the first one a string, the second one a number.
  2. If the length of the string is more than the given number, the string should be truncated to reduce the length so that it is equal the given number, and ... should be appended at the end of the truncated string.
  3. If the length of the string is equal to or lower than the given number, the string should be returned unchanged.

--hints--

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

js
assert.strictEqual(
  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....

js
assert.strictEqual(
  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.

js
assert.strictEqual(
  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.

js
assert.strictEqual(
  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....

js
assert.strictEqual(truncateString('A-', 1), 'A...');

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

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

--seed--

--seed-contents--

js

--solutions--

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

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