首页 > 解决方案 > 从 URL 的部分切片

问题描述

鉴于这些网址:

/content/etc/en/hotels/couver/offers/residents.html
/content/etc/en/offers/purchase.html

我想从 URL 中删除(切片)并仅获取/offers/residents/offers/purchase

我编写了这段代码来做到这一点,但我得到的结果与我需要的不同。请让我知道哪种语法可以按预期工作。

var test1 = '/content/etc/en/hotels/couver/offers/residents.html'
test1 = test1.slice(0,5);

var test2 = '/content/etc/en/offers/purchase.html'
test2 = test2.slice(0,5);

标签: javascriptjquery

解决方案


实现此目的的一种方法是将字符串拆分/,然后仅使用路径的最后两个部分来重建字符串:

['/content/etc/en/hotels/couver/offers/residents.html', '/content/etc/en/offers/purchase.html'].forEach(function(url) {
  var locs = url.replace(/\.\w+$/, '').split('/');
  var output = locs.slice(-2).join('/');
  console.log(output);
});

或者,您可以使用正则表达式仅检索您需要的部分:

['/content/etc/en/hotels/couver/offers/residents.html', '/content/etc/en/offers/purchase.html'].forEach(function(url) {
  var locs = url.replace(/.+\/(\w+\/\w+)\.\w+$/, '$1');
  console.log(locs);
});


推荐阅读