Replacing a string until it matches a certain length I'm trying to make an SMS Shortner for a kata at Codewars:


  Your task is to shorten the message to 160 characters, starting from end, by replacing spaces with camelCase, as much as necessary.


I've tried with a while loop and although the logic is correct, it's taking too long to process my tests. How can I optmize this and what parts are taking longer than it could?

const shortener = (message) =&gt; {
  let r = message.split('').reverse().join('');
  while (r.length &gt; 160) {
    r = r.replace(/([^\s]\s)/, (m,s) =&gt; s.trim().toUpperCase());
  }
  return r.split('').reverse().join('');
}
That is an O(L2) algorithm: each replace involves copying the entire string. A better strategy would be to call replace just once. First, figure out how many spaces need to be eliminated. Then, use a callback that conditionally modifies its match based on a count.

It should be possible to do it that way without reversing the string twice.