How to Truncate / Trim Text By Sentence in JavaScript (not word or character)

Many times for showing a preview of longer text, I prefer not just to show a certain amount of characters (although it looks better visually) but to break it via sentence. Below is a small JavaScript function (I use it in NodeJs a bunch) that I’ve used to do this. No, it’s not the most complicated thing ever, but I wanted to share in case it helps anyone.

String.prototype.truncateBySent = function(sentCount = 3, moreText = "") {
  //match ".","!","?" - english ending sentence punctuation
  var sentences = this.match(/[^\.!\?]+[\.!\?]+/g);
  if (sentences) {
    console.log(sentences.length);
    if (sentences.length >= sentCount && sentences.length > sentCount) {
      //has enough sentences
      return sentences.slice(0, sentCount).join(" ") + moreText;
    }
  }
  //return full text if nothing else
  return this;
};

Easy to use, just do something like this:

someText.truncateBySent(2);

Sometimes you also want to include something at the end to indicate there is more text, like a link or ellipsis. You can do this:

someText.truncateBySent(2,' <a href="#">View More</a>');

It will take a line of text like this:

Sample sentence one? Another sentence two. Another three. Is there four? What about five? And six! Finally seven.

And return this:

Sample sentence one? Another sentence two. View More

See a working sample here: https://codepen.io/chrisbitting/pen/oNvzKNz

Or grab it on GitHub: https://github.com/cbitting/jsTruncateBySentence

How to Truncate / Trim Text By Sentence in JavaScript (not word or character)

Leave a comment