javascriptstringurllocationpathname

How to combine pathname with URL strings


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':

Solution

  • 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");
        }