Home > Software design >  Slice returns full string rather than first num characters [closed]
Slice returns full string rather than first num characters [closed]

Time:09-16

The string is not being sliced. The full string is being returned, rather than just the first num characters.

function truncateString(str, num) {
      if (str.length > num) {
        str.slice(0,num)
        return str
      } else {
        return str
      }
}

console.log(truncateString("A-tisket a-tasket A green and yellow basket", 8))

CodePudding user response:

You need to return the result of the slice method:

function truncateString(str, num) {
      if (str.length > num) {
        return str.slice(0,num)
      } else {
        return str
      }
}

console.log(truncateString("A-tisket a-tasket A green and yellow basket", 8))

CodePudding user response:

function truncateString(str, num) {
      if (str.length > num) {
        return str.slice(0,num)
      } else {
        return str
      }
}

console.log(truncateString("A-tisket a-tasket A green and yellow basket", 7)) 

  • Related