Javascript Regex replace repetitions with exact one less

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)

hellonnngoodbye

Ans I want to convert it to this (n repeats 2 times)

hellonngoodbye

I know how to find out with regex when the occurrence repeats (e.g. /nn+/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?

Answer

You can search using this regex:

/n(n*)/g

And replace using: $1

RegEx Demo

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 ns in this capture group
  • Replacement of $1 will place all ns with back-reference of 1st capture group, thus reducing line breaks by one.

Code:

const string = 'hellonnngoodbye';
console.log(string);

const re = /n(n*)/g;
var repl = string.replace(re, "$1");

console.log(repl);