title: JavaScript replace all but last whilst preserving original line breaks
body: <p>I have some code which outputs as follows:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function replaceAllButLast(str, splitRegex, pOld, pNew) {
    var parts = str.split(splitRegex)
    if (parts.length === 1) return str
    return parts.slice(0, -1).join(pNew) + pOld + parts.slice(-1)
  }
  
  var str = "fred\r\nfred\r\nfred\r\n"
  var desiredResult = replaceAllButLast(str, /(?:\r?\n|\r)/, '\n', '\n+')
  
  console.log(desiredResult)</code></pre>
  </div>
  </div>
  </p>
  
  <p>The result is nearly as desired. However, the code assumes that the regex split operation is splitting on \n and thus is replacing it with \n</p>
  
  <p>However, it may actually be splitting on \r\n (windows - as in the example) or \r (old macs)</p>
  
  <p>Does anyone have some code that would give the same output as the code here BUT will preserve the original line break characters whilst still adding the + after a newline (except on the last line).</p>
  
  <p>I am using pure vanilla JavaScript.</p>
  
  <p>PS I must use the regex <code>/(?:\r?\n|\r)/</code></p>
  
  <p>PPS There is no need to use <code>.split()</code>.</p>