SoFunction
Updated on 2025-04-10

JavaScript method to truncate strings

This article describes the method of truncating strings by JavaScript. Share it for your reference. The details are as follows:

Here JavaScript truncates strings, similar to substr(), except that this function will not truncate words. After truncation occurs, an ellipsis will be added.

if (!function_exists('subsent')) {
  function subsent($string, $start = 0, $length = 0, $cap = '...') {
   if ($length <= 0 || strlen($string) < $length) { return $string; }
   $string = substr($string, $start, strpos($string, ' ', $length)) . ' ' . $cap;
   return $string;
  }
}

I hope this article will be helpful to everyone's JavaScript programming.