Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

94
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!