Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to remove hostname and port from URL?

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?

like image 468
Roy Tang Avatar asked Jan 14 '09 02:01

Roy Tang


2 Answers

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
like image 82
meouw Avatar answered Sep 25 '22 18:09

meouw


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(/^[^\/]/,'/');
}
like image 43
James Avatar answered Sep 24 '22 18:09

James