Skip to content

Truncate a string at a given length using JavaScript

This code snippet truncates or cuts off a text string after a certain number of characters and add an ellipsis (...) at the end.

Source: Coderrocketfuel

function truncateString(string, limit) {
  if (string.length > limit) {
    return string.substring(0, limit) + "..."
  } else {
    return string

truncateString("Sweet potato! They taste so good!", 10)
// returns "Sweet pota..."

truncateString("Sweet-potato!", 6)
// returns "Sweet-..."

truncateString("Mashed potatoes are better!", 50)
// returns "Mashed potatoes are better!"
See also  How to return multiple values from a JavaScript function?

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.