javascript - 从 URL 中提取某个值
问题描述
您认为从 window.location.href 中提取值的最佳方式是什么。
这是 http://localhost:3000/brand/1/brandCategory/3
路线始终相同的示例,只是数字会根据选择的内容而变化。
品牌 id 将是第一个数字,类别 id 是第二个我需要帮助在 react/typescript 项目中提取它们。
请记住,它应该在部署页面时工作,并且 URL 的开头将具有与 localhost 不同的名称,但路由将是相同的。
我尝试使用字符串格式进行操作,但它确实无法预测,也尝试使用正则表达式,但是当我尝试提取它时,关于对象的打字稿哭声可能是“空”,你有什么建议?
Number(window.location.href.match(new RegExp(/\/[0-9]\//,'gm'))[0].split('/')[1])
这是正则表达式尝试。
解决方案
您可以拆分路径,删除空段并按位置检索数字:
const url = 'http://localhost:3000/brand/1/brandCategory/3';
const segments = url.split('/').filter(seg => seg);
const length = segments.length;
console.log(`brand: ${segments[length - 3]}, brandCategory: ${segments[length - 1]}`);
我为尾部斜杠添加了过滤器。
您可以将过滤器替换为endsWith
const url = 'http://localhost:3000/brand/1/brandCategory/3';
const segments = url.split('/');
const length = url.endsWith('/') ? segments.length - 1 : segments.length;
console.log(`brand: ${segments[length - 3]}, brandCategory: ${segments[length - 1]}`);
推荐阅读
- java - 如何将 JsonObject 列表从 google json 转换为 Jackson 的 JsonNode 对象
- postgresql - 如何使用 postgresql 在购物车中生成唯一的交易 ID
- c# - 如何浏览所有带有路径的 Razor 视图?
- expo - 不分离/弹出的世博项目付款类型
- asp.net-core - 异步模型绑定asp.net核心?
- r - 列出子目录中以给定名称开头的文件 R
- reactjs - ExceptionsManager.js:74 TypeError: RNOneSignal.didSetNotificationOpenedHandler 不是函数
- php - laravel 串行函数背后的逻辑是什么?
- javascript - 如何修复 html2canvas 中的 div 位置
- react-native - 如何获取对象(歌曲)数组以存储在变量中