DEV Community

Cover image for Truncate... with this JS function...
Greg
Greg

Posted on • Updated on

Truncate... with this JS function...

const str= 'I am a very long string thats needs discipline!' 
function truncate(str, n) {
     return str?.length > n ? str.substr(0, n - 1) + '...' : str;
  } 

truncate(str,24);
Enter fullscreen mode Exit fullscreen mode

//'I am a very long string...'

The Gist

  • Pass the string onto the truncate function with the number indicating the the index of the string you want the ellipse(...) truncation to occur.

  • This versatile function does not only have to be 3 dots you can create 5 dots or any string character for that matter

❤️❤️❤️

Social

Twitter
Linkedin
Portfolio
Github

🤘

Happy Coding

Top comments (0)