20

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 }
Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
KittyYoung
  • 293
  • 1
  • 7
  • 11

5 Answers5

46
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"]
Mario Menger
  • 5,862
  • 2
  • 28
  • 31
  • 1
    Really like the simplicity of this. To remove any empty elements and have a nice array of the paths use this: `var locationPaths = location.pathname.split("/").filter(function(n){ return n != '' });` – JNP Web Developer May 22 '16 at 19:23
8

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

$.inArray("mine", window.location.pathname.split("/"))
derek
  • 4,826
  • 1
  • 23
  • 26
5
if (window.location.pathname.split("/")[2] == "mine") {
  // it exists
};

window.location.pathname is a string at the end of the day, so the usual string methods apply.

Matt
  • 74,352
  • 26
  • 153
  • 180
1

Even though this is a very old query.. it pops up in some search. So to add my notes.. over here

url.indexOf('mine') !== -1 

The above should be used for the check to find if url has a string... where as to find the path, it would be better off to use

var a = document.createElement('a');
a.href = url;
console.log(a.pathname);
// if url='http://localhost/messages/mine/9889'
// output will be /messages/mine/9889

hope this will save some ones time

0

You could use the string.split('/') function to create an array of items to check otherwise there are several jQuery plugins that parse the url eg

http://projects.allmarkedup.com/jquery_url_parser/

James Westgate
  • 11,306
  • 8
  • 61
  • 68