Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

84
Views
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)

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

let str = 'hello\n\n\ngoodbye'
console.log(str)
console.log(str.replace(/(\n*)\n/,'$1'))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!