Search code examples
javascriptjqueryregexregex-negationab-testing

How do I target a specifc folder in a url path using regex and window.location.href.indexOf()?


I am doing an a/b test that targets an element which has the same class name throughout different levels of a website:

e.g url: www.sitename.com/service-provided/state/region/city.

When I get to the city level page I dont want my code to run for the specific element. There are 100's of different cities so a list of url's to exclude is not the desired approach.

Is there a way using window.location.href.indexOf() and regex to only target the first three folders of the path?

Below is an example of what I am trying to achieve, If the url has any values in the first 3 folders of the path,only then run the code and not if the path goes into the 4th (city) folder.

$(document).ready(function () {
    if (window.location.href.indexOf("?/(.*)/(.*)/(.*)") > -1) {
       $(".className").css({"padding-right":"5%"});
     }
});

I'm open to any other method that might work.

Thanks.

Solution used:

p = window.location.pathname.split('/');

if (p.length < 5) {
     $(".className").css({"padding-right":"5%"});
}

Solution

  • You may achieve your goal with split and pathname. In this way you can pull the individual parts from your path:

    var p = window.location.pathname.split('/') - 1;
    /*
    www.sitename.com/service-provided/state/region/city
    pathArray = [service-provided, state, region, city]
    */
    if (p.length == 4) {
      state = pathArray[1];
      region = pathArray[2];
      city = pathArray[3];
    }