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

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

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 Denunciar

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