Reputation: 1062
I want to get the part of a URL after the last /
and before the querystring.
So far I had the last part of the URL, but I wasn't able to remove the querystring from the URL.
The Javascript:
<script type='text/javascript'>
var url = window.location.href;
var array = url.split('/');
var lastsegment = array[array.length-1];
document.write(lastsegment);
</script>
The structure of the URL is like this:
http://www.example.com/search/People?&results=latest
I only need the People
part. How could that be possible within the above Javascript?
Or is there any better way to do that?
Upvotes: 1
Views: 1401
Reputation: 11342
Try using window.location.pathname
instead of window.location.href
. It gets only the text between the server name and the query string (which is "/search/People"
in your case):
var last_part = window.location.pathname.split('/').pop();
You can read more about pathname
here.
Upvotes: 4
Reputation: 128
your code does the right thing, you could remove query strings by amending it a bit as;
var lastsegment = array[array.length-1];
if(lastsegment.indexOf('?'))
lastsegment = lastsegment.split('?')[0];
UPDATE: To handle the case if there are no query string embedded at all.
Upvotes: 2
Reputation: 85528
If you want to parse an URL from another origin than window.location
:
var test = 'http://www.example.com/search/People?&results=latest';
var parts = test.split('/');
lastPart = parts[parts.length-1].split('?')[0];
lastPart
is now "People"
Upvotes: 1
Reputation: 57095
Read Window.location
window.location.pathname.split('/').pop();
Upvotes: 2