javascript - 从 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);
解决方案
实现此目的的一种方法是将字符串拆分/
,然后仅使用路径的最后两个部分来重建字符串:
['/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);
});
推荐阅读
- node.js - 在 Apollo Graphql 中使用订阅时出错
- swift - 是否有可能快速函数获取
枚举? - php - 这是什么日期格式?2021-10-04T08:19:54.000+04:00
- php - 用户'root'@'localhost'的访问被拒绝(使用密码:YES)'
- html - 将 DIV 设置为背景图像的大小
- reactjs - 无法在 vscode 中调试 React 应用程序(模式:启动浏览器):当我启动调试浏览器实例时立即启动并关闭
- hyperledger-fabric - 在不同组织中分离订购者的 API 问题
- karate - 如何在单个线程中运行所有空手道功能文件,或者有什么方法可以自定义空手道中的线程数?
- unit-testing - 如果我已经有 100% 的单元测试覆盖率,我还需要更多的单元测试吗?
- python - 如何将一批图像帧转换为相同质量的视频