Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

244
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda