Truncate a String

xmohammedawad

Mohammed Awad

Posted on May 7, 2023

Truncate a String

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.

Examples

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

truncateString("A-tisket a-tasket A green and yellow basket",
 "A-tisket a-tasket A green and yellow basket".length)
//should return `A-tisket a-tasket A green and yellow basket.`
Enter fullscreen mode Exit fullscreen mode

My approach for solving this problem:

  • check the str length.
  • if the length is equal to num return str
  • if not return sliced str with num length

My solution:

function truncateString(str, num) {
  let slicedstr;

  if(str.length > num){
    slicedstr = str.slice(0,num)+"..."
  }else{
    slicedstr = str
  }

  return slicedstr;
}

truncateString("A-tisket a-tasket A green and yellow basket", 8)
Enter fullscreen mode Exit fullscreen mode

Any tips or edit are most welcome. share it with me on the comments. Thanks for being here!

Follow Muhmmad Awd on

If you have any questions or feedback, please feel free to contact me at

💖 💪 🙅 🚩
xmohammedawad
Mohammed Awad

Posted on May 7, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related