从URL中的部分中切片

时间:2019-03-16 14:58:39

标签: javascript jquery

给出以下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);

4 个答案:

答案 0 :(得分:1)

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

['/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);
});

答案 1 :(得分:0)

您可以使用正则表达式提取所需的子字符串。在下面的示例中,matches [1]将包含所需的子字符串。

var str = '/content/etc/en/hotels/couver/offers/residents.html';
var matches = str.match(/([\w]+\/[\w]+)\.html/);
var parsed = matches[1];

答案 2 :(得分:0)

这是什么意思? 更改切片编号?

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

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

答案 3 :(得分:0)

使用正则表达式删除从/ offers到.html结束的字符串前后的所有内容。

const str1 = '/content/etc/en/hotels/couver/offers/residents.html';
const str2 = '/content/etc/en/offers/purchase.html';

const regex = /^(.*)(\/offers\/.*)(.html)$/g;

console.log(str1.replace(regex, '$2')); // /offers/residents

console.log(str2.replace(regex, '$2')); // /offers/purchase

https://regex101.com/r/hRwLHi/1