Home > other >  JQuery multiple indexof on Windows location Href
JQuery multiple indexof on Windows location Href

Time:08-26

So I have this code that adds a class to my section whenever there's a url slug detected or contains that url.

<script type="text/javascript">
    jQuery(document).ready(function() {
      if (window.location.href.indexOf('product') > -1 || window.location.href.indexOf('about') > -1 || window.location.href.indexOf('careers') > -1 || window.location.href.indexOf('pricing') > -1) {
        $('#main-navigation-sec').addClass('product-nav-sec');
      }
    });
</script>

But this one might be too long to be inserted on the if condition for all. I'm trying out certain codes to make it into an array and can't seem to properly execute the right way. Any chance how to properly simplify it? It would be a great help. I'm referencing this array of indexOf here

CodePudding user response:

Here is a shortened version of your code using a single regex:

<script type="text/javascript">
    jQuery(document).ready(function() {
      if (window.location.href.match(/\/(product|about|careers|pricing)\b/)) {
        $('#main-navigation-sec').addClass('product-nav-sec');
      }
    });
</script>

Notice that this tests for a / followed by a keyword that is standalone, indicated by the word boundary \b. It's good to be specific in order to avoid false positives, such as https://example.com/foo/bar?utm=whereabouts

CodePudding user response:

let regex = /(?<=\/(product|about)\/)(.*)/; //add required path in brackets i.e. (product|about|careers)
let loc = regex.test(`/xyz/product/business-account/`);  //regex.test(window.location.href)
console.log('url matched: '   loc)
if(loc) {
    //Do you task
}

CodePudding user response:

Working on the assumption you want something to determine if the href contains one of a set of possible strings:

let possibilities = [ 'product', 'about', 'careers', 'pricing' ]

let containsAny = ( string, array ) => array.filter( elem => string.indexOf( elem ) > 0 ).length > 0

let foo = "bar"
let bar = "something about product goes here"

$(function() {
  if (containsAny(foo, possibilities)) { $('#main-navigation-foo').addClass('product-nav-foo') }
  if (containsAny(bar, possibilities)) { $('#main-navigation-bar').addClass('product-nav-bar') }  
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main-navigation-foo">inspect</div>
<div id="main-navigation-bar">these</div>

You could modify containsAny so it returned the positions of the matched elements instead of a boolean easily.

  • Related