Sammy Davis Sr.
Sammy Davis Sr.

Reputation: 13

How to grab the last bit of a url before the "?" in JavaScript?

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?

Upvotes: 1

Views: 1504

Answers (5)

daalbert
daalbert

Reputation: 1475

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

Upvotes: 1

sudipto
sudipto

Reputation: 2482

First remove the query-string by:

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

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 360016

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"]

Upvotes: 4

planetjones
planetjones

Reputation: 12633

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.

Upvotes: 2

DanielB
DanielB

Reputation: 20230

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];  
}

Upvotes: 0

Related Questions