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

334
Vistas
How to combine two regular expressions into one with different $1?

I have two regular expressions with different $1. In the first part, there is a slash before $1, but there is no slash in the second part. How then to combine them into one expression?

const url = 'http://localhost////example///author/admin?query=1212';
clean_url = url.replace(/($|\?)/, "/$1").replace(/([^:]\/)\/+/g, "$1")
console.log(clean_url)

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Since this question is asking about @nuxtjs/redirect-module, you can use multiple redirects:

redirect: [{
  from: '(.*)($|\?)(.*)',
  to: '$1/$2$3'
}, {
  from: '(.*)([^:]\/)\/+(.*)',
  to: '$1$2$3'
}]

or a replace function

redirect: [{
  from: '.*(?:(?:$|\?)|(?:[^:]\/\/+)).*',
  to: from => from.replace(/($|\?)/, "/$1").replace(/([^:]\/)\/+/g, "$1")
}]
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use

const url = 'http://localhost////example///author/admin';
clean_url = url.replace(/($|\?)|([^:]\/)\/+/g, (x,y,z) => z ? z : '/' + y);
console.log(clean_url);
// => http://localhost/example/author/admin/

The ($|\?)|([^:]\/)\/+ regex matches

  • ($|\?) - Group 1 (y): end of string or ?
  • | - or
  • ([^:]\/)\/+ - any char other than : and a / (Group 2, z), and then one or more slashes.

If Group 2 matches, the replacement is Group 2 value, else, the replacement is / + Group 3 value.

about 4 years ago · Juan Pablo Isaza Denunciar

0

It is not possible to just "combine" these two regular expressions, but you can combine the tasks, as both are just inserting a single / with different conditions.

You can combine the logic with lookbehinds (which may not be available in every browser yet) and the expression is an abomination and I'd be careful about performance in production; But it is possible ;)

const url = 'http://localhost////example///author/admin?query=1212';
clean_url = url.replace(/(?<!\?.*)(?<![:\/])(?:\/+|\/*(?=\?)|\/*$)/g, "/")
console.log(clean_url)

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