JavaScript: Truncating Returned Text from API

When retrieving text from the Trustpilot REST API, there may be occasions where the text string returned is extremely long - and you may need to truncate it for your own internal purposes, or onsite displays. 

For Example...

We can truncate text with a simple JavaScript function!

  function truncateText(text, limit) {
      const shortened = text.indexOf(' ', limit);
      if (shortened == -1) return text;
      return text.substring(0, shortened) + "...";

So this way, we can define a truncated version of the returned text string, like so:

note: the numeric value, 70 - is the character count we will count to until reviewText is truncated. 

let reviewTail = truncateText(reviewText, 70);

Then, we can insert this value instead of the raw reviewText. 

document.getElementById(idForTextLocation).innerHTML += "<p>" + reviewTail + "</p>";


Was this post helpful?


Sort by
Please sign in to leave a comment.