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

85
Visualizações
Regex - Replace part of url

I want to replace a part of url:

Origin-> https://example.u-test.com/ex-2<br>


Destination-> https://example.u-test.com/ex <br>

So what I want is to remove part after "-" but only in the second part after first slash.

With url.replace(/ *\-[^.]*\. */g, ".") I get:

https://example.u.com/ex-2

I want to remove "-2" after ex, not "-test" in the first part.

What is the right regex expression?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use the URL interface for that. it allows you to easily read and modify the different components of a given URL.

const url =  new URL("https://example.u-test.com/ex-2");

const domain = url.hostname;
const pathname = url.pathname;
const part = pathname.split("-")[0];

console.log(domain + part);

about 4 years ago · Juan Pablo Isaza Relatório

0

In case you absolutely want to do this with regular expressions:

const url = "https://example.u-test.com/ex-2"
const result = url.replace(/-[^-]*$/g, "")
console.log(result)

Explanation: If you want to remove the part after the last slash or dash, you should begin your match on that point. The above regular expression starts matching at the last dash (-) character in the line. Regex will match only the last dash because the subsequent characters it searches for is everything except another dash, followed by the end of the line ($).

  • - matches a dash (-) character
  • [^-]* matches everything except for another dash
  • $ after the dash and the non-dash characters, there must be the end of the line
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