Truncate a String (Challenge)

// According to FreeCodeCamp solutions:

function truncateString(str, num) {
  return str.length > num ? str.slice(0, num) + "..." : str;
truncateString("A-tiske a-tasket A green and yellow basket", 8);

// result = "A-tiske ..."
// This is not OK, because we have space before "...". My variant:

function truncate(str, num) {
  let newArr = str.split('')
  newArr.splice(num, newArr.length)

  return str.length <= num ? str
    : (str.length > num) ? (newArr.join('').trim() + "...")
      : str.trim() + "..."

truncate("A-tiske a-tasket A green and yellow basket", 8);

// result = "A-tiske..."
// OK

I have added spoiler tags.

Your variant is interesting, but it doesn’t technically meet the requirements.

Maybe technically yes, but if we test :

truncate("A      ending", 7)
// result  = "A      ..."

I don’t think that is good result

Like I said, your code is interesting but it isn’t a solution to the challenge. It’s a solution to a different problem.

It’s exactly what the requirements ask for, it’s not a challenge that requires consideration of edge cases and such

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.