Truncate a String
Mohammed Awad
Posted on May 7, 2023
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.`
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)
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
💖 💪 🙅 🚩
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
webdev String Matching Algorithm Uses, Interactive Implementations, & Free Source Code
November 4, 2021