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)
Post a Comment for "Javascript Replace All But Last Whilst Preserving Original Line Breaks"