Regex match for a string in a URL I feel like there is too much repetitive code going on here. All I am doing is doing a basic regex match for a string in the URL.

If a match is found, I find a li with a class (.index, .grid or .type) and add the active class. This is just for my main nav in an attempt to make it somewhat dynamic.

However, I feel like there is a more efficient way to code this:



$(document).ready(function() {
  var myLocation = window.location.href;
  var index = /index/i;
  var grid = /grid/i;
  var type = /type/i;
  var urlIndex = convertURL.match(index);
  var urlGrid = convertURL.match(grid);
  var urlType = convertURL.match(type);
  
  if (urlIndex) {
    $('.index').addClass('active');
  } else if (urlGrid) {
    $('.grid').addClass('active');
  } else if (urlType) {
    $('.type').addClass('active');
  }
});
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
Much like elclanrs' solution, just slightly more "plain"

$(function () {
  var classes = ['index', 'grid', 'type'],
      url = window.location.href.toLowerCase();
  for(var i = 0, l = classes.length ; i &lt; l ; i++ ) {
    if(url.indexOf(classes[i]) !== -1) {
      $('.' + classes[i]).addClass('active');
      break; // only first matching class is considered
    }
  }
});