I need to write some javascript to strip the hostname:port part from a url, meaning I want to extract the path part only.
i.e. I want to write a function getPath(url) such that getPath("http://host:8081/path/to/something") returns "/path/to/something"
Can this be done using regular expressions?
The window.location object has pathname, search and hash properties which contain what you require.
for this page
location.pathname = '/questions/441755/regular-expression-to-remove-hostname-and-port-from-url'
location.search = '' //because there is no query string
location.hash = ''
so you could use
var fullpath = location.pathname+location.search+location.hash
I know regular expressions are useful but they're not necessary in this situation. The Location object is inherent of all links within the DOM and has a pathname property.
So, to access that property of some random URL you could need to create a new DOM element and then return its pathname.
An example, which will ALWAYS work perfectly:
function getPath(url) {
var a = document.createElement('a');
a.href = url;
return a.pathname.substr(0,1) === '/' ? a.pathname : '/' + a.pathname;
}
jQuery version: (uses regex to add leading slash if needed)
function getPath(url) {
return $('<a/>').attr('href',url)[0].pathname.replace(/^[^\/]/,'/');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With