[英]How to use regex to extract the relative path of a url without path params or query params?
使用 NodeJS 环境,您将如何提取相对路径,同时不考虑数字路径参数和所有查询参数?
假设您有一个 url 作为字符串: https://localhost:8000/api/users/available/23342?name=john
目标是从中获取api/users/available
。 下面是一个实现,但是,它非常无效,并且必须通过正则表达式完成所有操作来获得更好的解决方案......
const url = 'https://localhost:8000/api/users/available/23342?name=john';
url
.split("/")
.splice("3")
.join("/")
.split("?")[0]
.replace(/\/(\d*)$/, "");
};
您可以使用单个正则表达式替换 url。 这是带有一堆要测试的url的代码:
const urls = [ 'https://localhost:8000/api/users/available/23342?name=john', 'https://example.com/api/users/available/23342?name=john', 'https://example.com/api/users/available/23342', 'https://example.com/api/users/available?name=john', ]; const regex = /^[az]+:\/\/[^:\/]+(:[0-9]+)?\/(.*?)(\/[0-9]+)?(\?.*)?$/; urls.forEach((url) => { var result = url.replace(regex, '$2'); console.log(url + ' ==> ' + result); });
Output:
https://localhost:8000/api/users/available/23342?name=john ==> api/users/available
https://example.com/api/users/available/23342?name=john ==> api/users/available
https://example.com/api/users/available/23342 ==> api/users/available
https://example.com/api/users/available?name=john ==> api/users/available
正则表达式搜索和替换的解释:
^
... $
- 开始和结束的锚点[az]+:\/\/
- 扫描协议和://
[^:\/]+
- 扫描域名(任何在:
或/
(:[0-9]+)?
- 扫描端口号( ?
使前面的捕获成为可选的)\/
- 扫描/
(url 路径的第一个字符)(.*?)
- 非贪婪地扫描和捕获任何东西,直到:(\/[0-9]+)?
- 扫描/
和数字字符(如果有)(\?.*)?
- 扫描查询参数,如果有的话'$2'
,例如仅使用第二个捕获,我们的 url 路径不包括数字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.