I'm trying to use a switch statement:
var currentURL = window.location.href;
switch(currentURL)
{
// Home page
case "http://localhost/myWebsitePath/":
alert("Home!");
break;
// Blog home page
case "http://localhost/myWebsitePath/blog/":
alert("Blog!");
break;
}
When visiting http://localhost/myWebsitePath/, I get the alert. When visiting http://localhost/myWebsitePath/blog/, I don't always get the alert. It seems to sometimes work when clicking a hyperlink from home page. Do I need to escape any special characters to guarantee it works?
Note: both paths have their respective index.html files in the folders
console.log(currentURL);
console.log(typeof(currentURL));
Produces:
http://localhost/myWebsitePath/blog/ string
Seems to now work correctly if I use:
var currentURL = window.location.href;
currentURL = encodeURIComponent(currentURL);
Then switch case as follows:
switch(currentURL)
{
// Home page
case "http%3A%2F%2Flocalhost%2FmyWebsitePath%2F":
alert("Home!");
break;
// Blog home page
case "http%3A%2F%2Flocalhost%2FmyWebsitePath%2Fblog%2F":
alert("Blog!");
break;
}
I used https://meyerweb.com/eric/tools/dencoder/ to encode/decode the URLs initially and insert those into my switch cases.