Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

337
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda