在前端开发中,经常需要从URL路径中提取特定参数。本文将详细介绍使用JavaScript正则表达式从URL中提取斜杠(/ )之间值的3种专业方法。
const url = 'https://example.com/users/12345/profile';
const matches = url.match(/\/([^\/]+)\/?/g);
console.log(matches); // [ "/users/", "/12345/", "/profile" ]
此方法使用[^\/]+匹配非斜杠字符,g标志进行全局搜索。
function getPathSegment(url, index) {
const segments = url.split('/').filter(Boolean);
return segments[index];
}
const userId = getPathSegment(window.location.pathname, 2);
console.log(userId); // 输出第二个斜杠间的值
const regex = /\/(?[^\/]+)\/?(?[^\/]+)?\/?/;
const { groups } = regex.exec('/products/electronics');
console.log(groups.segment1); // "products"
console.log(groups.segment2); // "electronics"
通过这三种方法,您可以灵活应对各种URL路径解析需求。根据项目环境选择最适合的方案,平衡开发效率与运行性能。