如何将路径名与 URL 字符串组合

How to combine pathname with URL strings

我正在设置 javascript,其中包含多个 URLS 的路径名,但我不想为连续 URL 设置新的 "case" ] 字符串。

是否有任何可能的解决方案来组合路径名大小写而不是创建一个新的?

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;
}

我曾想过一个简单的技巧就是像这样添加“+”...(但没有成功)

case '/blog/category/style' + '/blog/category/style/2':

您可以使用这种 Switch Cases 组合它们(如果它们具有相同的输出命令):

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;
}

您实际上可以省略 break 语句并控制 "fall through" 到下一个响应。

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;
}

我认为如果您总是这样做,则不需要使用 switch。将这些路径放在一个数组中,然后简单地检查 window.location.pathname 是否在数组中,并取决于是否添加样式。

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