Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

247
Views
Switch case not working with URLs [JavaScript]

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!