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/?f开发者_运维技巧oo=bar&hello=bye
How can I still get "welcome" and disregard everything that comes after it?
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"]
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.
lastBit = window.location.pathname.match(/\/([^\/]+?)\/(?:\?|$)/i)[1];
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];
}
First remove the query-string by:
url = window.location.href.replace(window.location.search, "");
精彩评论