danday74
danday74

Reputation: 56936

JavaScript replace all but last whilst preserving original line breaks

I have some code which outputs as follows:

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)

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

However, it may actually be splitting on \r\n (windows - as in the example) or \r (old macs)

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).

I am using pure vanilla JavaScript.

PS I must use the regex /(?:\r?\n|\r)/

PPS There is no need to use .split().

Upvotes: 1

Views: 612

Answers (2)

Alex Undefined
Alex Undefined

Reputation: 630

I've replaced your regexp with visible chars so you can see what's going on:

var input = "fredEOLfredENDLfredFINfred";
input = input.replace(/(EOL|ENDL|FIN)/g, "$1+");
console.log(input);

Upvotes: 1

leaf
leaf

Reputation: 1764

This will keep the last newline as it is but others added a +, see replace

var str = "fred\r\nfred\r\nfred\r\n";
var splitRegexp = new RegExp(/(?:\r?\n|\r)/, 'g')

var newstr = str.replace(splitRegexp, function(match, offset, string) {
  var follow = string.slice(offset);
  var isLast = follow.match(splitRegexp).length == 1;

  if (!isLast) {
    return match + '+';
  } else {
    return match;
  }
})
console.log(newstr)

Upvotes: 1

Related Questions