I am attempting to extract the base URL from a string without using window.location.
- It must eliminate the trailing slash
- It must be done using regex instead of New URL
- It should handle query parameters and anchor links
In essence, all of the following examples should result in https://apple.com
or https://www.apple.com
for the last one.
https://apple.com?query=true&slash=false
https://apple.com#anchor=true&slash=false
http://www.apple.com/#anchor=true&slash=true&whatever=foo
These are just sample URLs, variations like
https://shop.apple.co.uk/?query=foo
should yield https://shop.apple.co.uk
- It could be any URL like: https://foo.bar
The closest I've gotten is with:
const baseUrl = url.replace(/^((\w+:)?\/\/[^\/]+\/?).*$/,'$1').replace(/\/$/, ""); // Base Path & Trailing slash
However, this solution fails when dealing with anchor links and queries that directly follow the URL without a preceding /
.
Do you have any suggestions on how to make it work for all scenarios?