1

I'm using this to grab the last part of the url:

url = window.location.href;                             
parts = url.split("/");

if (parts[parts.length-1].length == 0) {
    lastBit = parts[parts.length-2];
} else {
    lastBit = parts[parts.length-1];  
}

The above works with or without a forward slash. So if my url was:

http://mysite.com/path/to/welcome/

I would get just this:

welcome

But what if my url is:

http://mysite.com/path/to/welcome/?foo=bar&hello=bye

How can I still get "welcome" and disregard everything that comes after it?

5 Answers 5

4

How about

var urlWithoutSearch = location.href.replace(location.search, '');

Just use location.pathname:

var parts = window.location.pathname.replace(/\/$/, '').split('/'),
    lastBit = parts[parts.length - 1];

The replace() gets rid of a trailing / character, if present. (We don't care about a leading / in this case.)

Ex.

> '/path/to/welcome/'.replace(/\/$/, '').split('/')
> ["", "path", "to", "welcome"]
2

Look at window.location.pathname and work with this. This variable just includes the path and does not include any query parameters. So in your example you would be left with /path/to/welcome and parsing that is trivial.

1
lastBit = window.location.pathname.match(/\/([^\/]+?)\/(?:\?|$)/i)[1];
0

Do a split on ? before.

url = window.location.href;                             
urlParts = url.split('?');
parts = urlParts[0].split("/");

if (parts[parts.length-1].length == 0) {
    lastBit = parts[parts.length-2];
} else {
    lastBit = parts[parts.length-1];  
}
0

First remove the query-string by:

url = window.location.href.replace(window.location.search, "");

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.