Home > Enterprise >  Javascript Regex replace repetitions with exact one less
Javascript Regex replace repetitions with exact one less

Time:10-20

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?

CodePudding user response:

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 = 'hello\n\n\ngoodbye';
console.log(string);

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

console.log(repl);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

replace (\n*)\n with $1?

let str = 'hello\n\n\ngoodbye'
console.log(str)
console.log(str.replace(/(\n*)\n/,'$1'))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related