DEV Community

Randy Rivera
Randy Rivera

Posted on

Truncate a string

  • Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a ... ending.
function truncateString(str, num) {
  return str;
}

truncateString("A-tisket a-tasket A green and yellow basket", 8);
Enter fullscreen mode Exit fullscreen mode
  • First let's see how slice works:
// slice() method should work for this as well; whats slice?
let name = "randy";
console.log(name.slice(0, 3)); // will display ran
Enter fullscreen mode Exit fullscreen mode
  • Answer:
function truncateString(str, num) {
  if (str.length > num) {
    return str.slice(0, num) + "...";
  }
  return str;
}

console.log(truncateString("A-tisket a-tasket A green and yellow basket", 8)); // will display "A-tisket..."
// console.log("A-tisket a-tasket A green and yellow basket".length); will display 43
Enter fullscreen mode Exit fullscreen mode

Top comments (0)