Reputation: 455
I have a string which has a character (\n
) repeated multiple times. I want to replace this repetitions by just one repetition less.
So let's suppose that we have a string like this (\n repeats 3 times)
hello\n\n\ngoodbye
Ans I want to convert it to this (\n repeats 2 times)
hello\n\ngoodbye
I know how to find out with regex when the occurrence repeats (e.g. /\n\n+/g
), but I don't know how to capture the exact number of repetitions to use it in the replace.
Is possible to do that with Regex?
Upvotes: 2
Views: 616
Reputation: 785246
You can search using this regex:
/\n(\n*)/g
And replace using: $1
RegEx Details:
\n
: Match a line break(\n*)
: Match 0 or more line breaks and capture them in 1st capture group. Note that we are capturing one less \n
s in this capture group$1
will place all \n
s with back-reference of 1st capture group, thus reducing line breaks by one.Code:
const string = 'hello\n\n\ngoodbye';
console.log(string);
const re = /\n(\n*)/g;
var repl = string.replace(re, "$1");
console.log(repl);
Upvotes: 4
Reputation: 10746
replace (\n*)\n
with $1
?
let str = 'hello\n\n\ngoodbye'
console.log(str)
console.log(str.replace(/(\n*)\n/,'$1'))
Upvotes: 2