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 and 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
//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

chunk: 2

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

Khayrattee Wasseem's Picture

About Khayrattee Wasseem

PHP enthusiast | The PHP Community Fanboi | Founder of PHP Usergroup for Mauritius (#PhpMauritius) | Aspiring Entrepreneur | Ex-country Manager of a global award winning Magento Agency | Passionate about all things Wordpress & Servers


1 comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.