0

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%"});
}
kennyi
  • 23
  • 1
  • 5

2 Answers2

1

like this

const someURLs = [
  'www.sitename.com/massage/new-york/east-coast/manhatan',
  'www.sitename.com/massage/new-york/east-coast/bronx',
  'www.sitename.com/massage/texas/south/austin',
  'www.sitename.com/accounting/texas/south/atlanta',
];

const firstThreeFolders = /\/([^\/]+\/){3}/;

someURLs.forEach(url => {

  console.log( url.match(firstThreeFolders)[0] );

});

explanation:

match a forward slash, followed by anything that is not a forward slash any number of times, repeat that thrice.

code_monk
  • 9,451
  • 2
  • 42
  • 41
1

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];
}
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
pg316
  • 1,380
  • 1
  • 8
  • 7
  • Hey gaetanoM. Thanks for trying to improve the answer. I am wondering why you changed the length to 4 though and added a -1 to the declaration. It sounds like kennyi wants to perform an action when there are 3 folders. I gave an example of the split pathArray values. Can you explain your updates a bit more? – pg316 Aug 08 '18 at 21:38
  • Thanks for your help. I ended up just needing to split the path into an array and using p.length < 3 to execute the code in the if statement. – kennyi Aug 10 '18 at 18:14