Cropping a message using array splits I am trying to write a simple function to crop a given message to a specific length but at the same time not to cut the words in between and no trailing spaces in the end.

Example: 

Input String: The quick brown fox jumped over the fence, K: 11

Output: The quick

Here is what I have tried:

  function crop(message, K) {
  var originalLen = message.length;
  if(originalLen&lt;K)
  {
      return message;
  }
  else
  {
      var words = message.split(' '),substr;

      for(var i=words.length;i &gt; 0;i--)
       {

           words.pop();

            if(words.join(' ').length&lt;=K)
            {
              return words.join(' ');
            }
       }


  }
}


This function works fine but I am not very happy with the implementation. Need suggestions on the performance aspects and will there be a case where this won't work?
This is much slower than necessary.  It takes time to construct the array, and more to shorten the array word-by-word.  It's easy to imagine how this would go if words contains a whole book and K is some small number.

In general, you want an approach that inspects the original string to decide how much to keep, and then extracts that much, once, before returning it.

A regular expression is an efficient and compact way to find text that meets your criteria.  Consider:

function crop(message, K) {
    if(K&lt;1) return "";
    const reK = new RegExp( `^.{0,${K-1}}[^ ](?= |$)` );
    return ( message.match(reK) || [ "" ] )[0];
}


.match returns an array with the matched text as the first element, or null if no match.  The alternative [ "" ] will provide an empty string as a return value if there is no match (when the first word is longer than K). 

The regular expression, broken down, means:


^: match start of string
.: followed by any character
{0,10}: ... up to ten times (one less than K)
[^ ]: followed by a character that is not a space
(?=…): this is an assertion; it means the following expression must match, but is not included in the result:


: followed by a space
|: or
$: end-of-string



Exercise: can you generalize this approach to recognize any kind of whitespace (tabs, newlines, and so on)?