如何使用正则表达式提取没有路径参数或查询参数的 url 的相对路径?

在 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*)$/, "");

};


幕布斯7119047
浏览 142回答 1
1回答

慕森卡

您可以使用单个正则表达式来替换 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/availablehttps://example.com/api/users/available/23342?name=john ==> api/users/availablehttps://example.com/api/users/available/23342 ==> api/users/availablehttps://example.com/api/users/available?name=john ==> api/users/available正则表达式搜索和替换的说明:^... $- 在开始和结束处锚定[a-z]+:\/\/- 扫描协议并://[^:\/]+- 扫描域名(任何之前:或之前的内容)/(:[0-9]+)?- 扫描端口号(这?使得前面的捕获成为可选)\/- 扫描/(url路径的第一个字符)(.*?)- 非贪婪地扫描和捕获任何内容,直到:(\/[0-9]+)?- 扫描 a/和 number 字符(如果有)(\?.*)?- 扫描查询参数(如果有)替换:'$2',例如仅使用第二个捕获,其中使用不包括数字的 url 路径
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript