Skip to content Skip to sidebar Skip to footer

Javascript Replace All But Last Whilst Preserving Original Line Breaks

I have some code which outputs as follows: The result is nearly as desired. However, the code assumes that the regex split operation is splitting on \n and thus is replacing it wi

Solution 1:

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 = newRegExp(/(?:\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)

Solution 2:

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

Post a Comment for "Javascript Replace All But Last Whilst Preserving Original Line Breaks"