Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - how to remove domain from location.href

I need to remove the domain name from location.href using Javascript. I have links like: http://localhost/App/User/UserOrder.aspx?id=949abc91-a644-4a02-aebf-96da3ac7d8e1&type=MO and I need to have links without http://localhost and in future without it's real domain name.

I will use those trimed links in Javascript function so I would like to trim it also in Javascript.

I have tried: window.location.href.split('/')[2]; but I could only get domain form it. And I want to get rid of domain.

Any help here much appreciated!

like image 854
Marta Avatar asked Aug 04 '11 16:08

Marta


3 Answers

Use window.location.pathname. This gives you the path relative to the host. See here for more details.

For any arbitrary URL, assuming that the variable url contains your URL, you can do:

url = url.replace(/^.*\/\/[^\/]+/, '')
like image 150
Vivin Paliath Avatar answered Nov 01 '22 00:11

Vivin Paliath


Rather than doing string manipulation on window.location.href, you can use the other properties of window.location. In your case, you want the pathname, the search and the hash:

console.log(window.location.pathname + window.location.search + window.location.hash);
like image 16
Dan Davies Brackett Avatar answered Nov 01 '22 00:11

Dan Davies Brackett


I posted this on your other question as a comment but I might as well add it here too. You can use a replace with a regex, like this:

location.href.replace(/.*\/\/[^\/]*/, '')

like image 10
alnorth29 Avatar answered Nov 01 '22 00:11

alnorth29