The Muffin Man
The Muffin Man

Reputation: 20004

Javascript match part of url, if statement based on result

Here is an example of the url i'm trying to match: http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx

What im trying to match is http: //store.mywebsite.com/folder-1 except that "folder-1" will always be a different value. I can't figure out how to write an if statement for this:

Example (pseudo-code)

if(url contains http://store.mywebsite.com/folder-1)
do this

else if (url contains http://store.mywebsite.com/folder-2)
do something else

etc

Upvotes: 2

Views: 7337

Answers (4)

LaustN
LaustN

Reputation: 720

In the interest of keeping things very simple...

if(location.pathname.indexOf("folder-1") != -1)
{
    //do things for "folder-1"
}

this might give you false positives if the value "folder-1" could be present in other parts of the string. If you are already making sure this is not the case, the provided example should be sufficient.

Upvotes: 5

Andy E
Andy E

Reputation: 344675

I would split() the string and check an individual component of the url:

var str = "http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx"

// split the string into an array of parts
var spl = str.split("/");

// spl is now [ http:,,store.mywebsite.com,folder-1,folder-2,item3423434.aspx ]
if (spl[4] == "folder-1") {
    // do something
} else if (spl[4] == "folder-2") {
    // do something else
}

Using this method it's easy to check other parts of the URL too, without having to use a regular expression with sub-expression captures. e.g. matching the second directory in the path would be if spl[5] == "folder-x".

Of course, you could also use indexOf(), which will return the position of a substring match within a string, but this method is not quite as dynamic and it's not very efficient/easy to read if there are going to be a lot of else conditions:

var str = "http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx"
if (str.indexOf("http://store.mywebsite.com/folder-1") === 0) {
    // do something
} else if (str.indexOf("http://store.mywebsite.com/folder-2") === 0) {
    // do something
}

Upvotes: 4

msurovcak
msurovcak

Reputation: 481

Just use URL parting in JS and then you can match URL's against simple string conditions or against regular expressions

Upvotes: 0

maerics
maerics

Reputation: 156534

Assuming the base URL is fixed and the folder numbers can be very large then this code should work:

var url = 'http://store.mywebsite.com/folder-1/folder-2/item3423434.aspx'
  , regex = /^http:..store.mywebsite.com.(folder-\d+)/
  , match = url.match(regex);
if (match) {
  if (match[1] == 'folder-1') {
    // Do this
  } else if (match[1] == 'folder-2') {
    // Do something else
  }
}

Upvotes: 0

Related Questions