Get base URL
JavaScript, String, Browser, Regexp · Jan 3, 2021

Gets the current URL without any parameters or fragment identifiers.
- Use
String.prototype.replace()
with an appropriate regular expression to remove everything after either'?'
or'#'
, if found.
const getBaseURL = url => url.replace(/[?#].*$/, '');
getBaseURL('http://url.com/page?name=Adam&surname=Smith');
// 'http://url.com/page'
Written by Angelos Chalaris
I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.
If you want to keep in touch, follow me on GitHub.