1 回答
TA贡献1806条经验 获得超8个赞
您可以使用单个正则表达式来替换 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 = /^[a-z]+:\/\/[^:\/]+(:[0-9]+)?\/(.*?)(\/[0-9]+)?(\?.*)?$/;
urls.forEach((url) => {
var result = url.replace(regex, '$2');
console.log(url + ' ==> ' + result);
});
输出:
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
正则表达式搜索和替换的说明:
^...$- 在开始和结束处锚定[a-z]+:\/\/- 扫描协议并://[^:\/]+- 扫描域名(任何之前:或之前的内容)/(:[0-9]+)?- 扫描端口号(这?使得前面的捕获成为可选)\/- 扫描/(url路径的第一个字符)(.*?)- 非贪婪地扫描和捕获任何内容,直到:(\/[0-9]+)?- 扫描 a/和 number 字符(如果有)(\?.*)?- 扫描查询参数(如果有)替换:
'$2',例如仅使用第二个捕获,其中使用不包括数字的 url 路径
添加回答
举报
