StudentRik
StudentRik

Reputation: 1049

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

Upvotes: 1

Views: 88

Answers (3)

user3589620
user3589620

Reputation:

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

Upvotes: 1

Shushanth Pallegar
Shushanth Pallegar

Reputation: 2862

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; 

Upvotes: 1

Blake Yarbrough
Blake Yarbrough

Reputation: 2316

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

Upvotes: 2

Related Questions