Javascript Snippet To Find If URL Contains Page Name

Finding if the url contains part of a page name can be useful in some cases. Such a situation might arise for instance when you are calling a javascript function on more than one page.

Example, let’s consider both of the following pages http://7php.com/page1.php and http://7php.com/page2.php call the same method CallMe(). Assuming that you want each of these pages to do something additional and that you want to do this by verifying if the url contains the desired page name, one possible solution might be:

var Page1 = "page1.php";
var Page2 = "page2.php";

var thisUrl = decodeURI(window.location);
var urlChunks = thisUrl.split("/");
for (var chunk in urlChunks)
{
    alert('chunk: ' + chunk);
    alert('urlChunks[chunk]: ' + urlChunks[chunk]);

    if (urlChunks[chunk] == Page1) //If the URL contains something (page 1)... do this
    {
        alert('inside index.html');
        //logic X
        //something additional for page 1
    }
    else if (urlChunks[chunk] == Page2) //If the URL contains something (page)... do that
    {
         //logic X
        //something additional for page 2
    }
    else
    {
        //do a default action
    }
}

Let’s Analyse What This Code Does

I have included some alerts in the code for the purpose of ‘tracing’ the code execution.
Consider our url to be “file:///C:/Users/kwasseem/Desktop/index.html
When execution enters the loop, we will get the following responses (alerts):

chunk: 0
urlChunks[chunk]: file:

chunk: 1
urlChunks[chunk]:

chunk: 2
urlChunks[chunk]:

chunk: 3
urlChunks[chunk]: C:

chunk: 4
urlChunks[chunk]: Users

chunk: 5
urlChunks[chunk]: kwasseem

chunk: 6
urlChunks[chunk]: Desktop

chunk: 7
urlChunks[chunk]: index.html
inside index.html

If You Appreciate What I Do Here On Seven PHP :: 7PHP, You Could Consider:

  1. Following me on Twitter | @7php
  2. LIKE-ing my FaceBook page
  3. Subscribe to my Email List - see top-right subscription box
  4. Help diffuse this interview to the PHP ecosystem - Share & Spread the word as far as you can ==> That would be a FREE way to thank me
  5. Use my DigitalOcean referral link if you plan to use it as your VPS (it starts at only $5/month btw) or if you can refer it to your friends, highly appreciated.
  6. Support via Paypal donate - my Paypal ID is w@7php.com

{I'm thankful to your response(s)!}

Valuable Feedback / Comment / Review From People Like You

  1. Salah Kaddumi says:

    Thanks a lot

Speak Your Mind

*