简体   繁体   中英

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

I am trying to concat a regex to a case statement:

I basically want to match a url that is news/asdd-asdadas-assas.aspx

I have other url's matched for added an active class to the navigation. The urls are made from page routes.

I have been doing this 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;

and so on ..

but i want to do this:

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

I have tried many different Regex, am I doing it the correct way with the case ?

How will I match the url by concatenating the re variable

That is not the proper way to use regex in Javascript . Regex matching returns true/false. This means that in your case statements you would end up with something like

pathName === pathName.match(re)

which translates to

pathName === true or pathName === false

which may actually evaluate if pathName is not null or undefined , but almost certainly will not result in the behavior that you are expecting.

EDIT: it looks like according to this reference provided by @JonathanM, that the case statement almost certainly will not evaluate when the parameter passed into the switch evaluates to either true or false.

Would you consider modifying your code to use the .match() method?

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

you can use test method of regular expressions , which returns true if it matches

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

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

Your solution does not work, because you are using a regex in your case statement. One has to match the regex and than put it in the case statement:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM