-1

I'm setting up javascript that contains pathname for multiple URLS, but I don't want to set up a new "case" for the continual URL string.

Is there any possible solution to combine pathname cases instead of creating a new one?

switch (window.location.pathname) {
case '/blog/category/style':
$(".wsite-sideblock h2.wsite-title").append("Style");
break;
case '/blog/category/style/2':
$(".wsite-sideblock h2.wsite-title").append("Style");
break;
case '/blog/category/style/3':
$(".wsite-sideblock h2.wsite-title").append("Style");
break;
.
.
.
case '/blog/category/style/10':
$(".wsite-sideblock h2.wsite-title").append("Style");
break;
}

I had a thought that a simple trick is to add "+" like this... (but it didn't work)

case '/blog/category/style' + '/blog/category/style/2':
Grets
  • 31
  • 9

3 Answers3

1

You can combine them using this sort of Switch Cases (if they have the same output command):

switch (window.location.pathname) {
case '/blog/category/style':
case '/blog/category/style/2':
case '/blog/category/style/3':
...
case '/blog/category/style/10':
$(".wsite-sideblock h2.wsite-title").append("Style");
break;
}
ChupaXL
  • 11
  • 1
1

I think you don't need to use switch if you will always do the same. Put these paths in an array and simple check if window.location.pathname is in the array or not and depending on that add style or not.

    const paths = ['/blog/category/style', '/blog/category/style/2', ..., '/blog/category/style/10'];
    if (paths.includes(window.location.pathname)) {
        $(".wsite-sideblock h2.wsite-title").append("Style");
    }
StefanRado
  • 66
  • 3
0

You can actually just omit the break statements and control will "fall through" to the next response.

let pathname = '/blog/category/style/3';

switch (pathname) {
  case '/blog/category/style':
  case '/blog/category/style/2':
  case '/blog/category/style/3':
  case '/blog/category/style/10':
    console.log("Print this for any of the above cases");
    break;
}
Cat
  • 4,141
  • 2
  • 10
  • 18