Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - get url path?

I know I can use window.location.pathname to return a url, but how do I parse the url?

I have a url like this: http://localhost/messages/mine/9889 and I'm trying to check to see if "mine" exists in that url?

So, if "mine" is the second piece in that url, I want to write an if statement based on that...

if(second argument == 'mine') { do something }
like image 952
KittyYoung Avatar asked Apr 19 '10 14:04

KittyYoung


People also ask

How can I get url in jQuery?

The current URL in jQuery can be obtained by using the 'href' property of the Location object which contains information about the current URL. The 'href' property returns a string with the full URL of the current page.

How do you get the current page url?

Answer: Use the window. location. href Property location. href property to get the entire URL of the current page which includes host name, query string, fragment identifier, etc.

Which method return the url of the current page?

The window.location.href property returns the URL of the current page.


2 Answers

if ( location.pathname.split("/")[2] == "mine" ) { do something }

Although it would obviously be better to check whether there are enough items in the array that's returned by split:

var a = location.pathname.split("/");
if ( a.length > 2 && a[2] == "mine" ) { do something }

Note that even though array indexes are zero based, we want to specify 2 as the index to get what you refer to as the 2nd argument as split splits "/messages/mine/9889" into an array of 4 items:

["", "messages", "mine", "9889"]
like image 87
Mario Menger Avatar answered Sep 22 '22 15:09

Mario Menger


if jquery is an option, you could do the following:

$.inArray("mine", window.location.pathname.split("/"))
like image 37
derek Avatar answered Sep 22 '22 15:09

derek