如何使用正则表达式和 window.location.href.indexOf() 定位 url 路径中的特定文件夹?

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

我正在做一个 a/b 测试,目标是在网站的不同级别具有相同 class 名称的元素:

例如url:www.sitename.com/service-provided/state/region/city.

当我到达城市级别页面时,我不希望我的代码针对特定元素 运行。有 100 个不同的城市,因此要排除的 url 的列表不是所需的方法。

有没有办法使用 window.location.href.indexOf() 和正则表达式来仅定位路径的前三个文件夹?

下面是我想要实现的示例,如果 url 在路径的前 3 个文件夹中有任何值,只有 运行 代码而不是路径进入第四个(城市)文件夹。

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

我愿意接受任何其他可能有效的方法。

谢谢。

使用的解决方案:

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

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

像这样

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] );

});

说明:

匹配一个正斜杠,然后匹配任何不是正斜杠的内容任意多次,重复三次。

您可以通过 split and pathname 实现您的目标。通过这种方式,您可以从您的路径中拉出各个部分:

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];
}