Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

83
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda