Home > other >  Regex - Replace part of url
Regex - Replace part of url

Time:09-18

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?

CodePudding user response:

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

CodePudding user response:

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