DEV Community

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

Posted on • Edited on

2 2

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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay