在带有 Javascript 的 case 语句中打开正则表达式比较的结果

Switching on the result of a regex comparison in a case statement with Javascript

我正在尝试将正则表达式连接到 case 语句:

我基本上想匹配一个 url 即 news/asdd-asdadas-assas.aspx

我有其他 url 的匹配添加了一个活跃的 class 到导航。 urls 由页面路由组成。

我一直在做这个var pathName = window.location.pathname;

var re = "/[^news][\w\W]+/";
switch (pathName) {
    case "/":
        $('#home-active').addClass('active');
        break;
    case "/about-us.aspx":
        $('#about-active').addClass('active');
        break;

等等..

但我想这样做:

case "/news"+re:
        $('#news-active').addClass('active');
        break;    

我尝试了很多不同的正则表达式,我使用 case 的方式是否正确?

如何通过连接 re 变量来匹配 url

你可以使用正则表达式的测试方法,如果匹配returns则为真

  var re = /[^news][\w\W]+/;

      case "/news".match(re)[0]:
          $('#news-active').addClass('active');
          break; 

这不是在 Javascript 中使用正则表达式的正确方法。正则表达式匹配 returns true/false。这意味着在你的案例陈述中你最终会得到类似

pathName === pathName.match(re)

转换为

pathName === truepathName === false

如果 pathName 不是 nullundefined 可能 实际评估,但几乎肯定不会导致您的行为期待中。

编辑:根据@JonathanM 提供的this 参考,当传递到开关的参数的计算结果为真或假时,case 语句几乎肯定不会计算。

您会考虑修改您的代码以使用 .match() 方法吗?

if(pathName.match(re)){
    $('#home-active').addClass('active');
}else if(pathName.match(re2)){
    $('#about-active').addClass('active');
}

您的解决方案不起作用,因为您在 case 语句中使用了正则表达式。必须匹配正则表达式并将其放在 case 语句中:

var url = "news/asdd-asdadas-assas.aspx";
var regex = new RegExp('\/.*?(.aspx)', 'g'); // from '/' to '.aspx'
var match = url.match(regex)[0]; // matches everything behind news and returns a string

case("/news" + match) ...

Example