1

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?

1
  • this is one of the most often asked js-question i see on SO Commented Feb 21, 2014 at 14:45

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Read Window.location

window.location.pathname.split('/').pop();

.pop()

2 Comments

The last part may not be the 3rd item of the array.
And your solution is very similar to mine.
2

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.

Comments

1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.