首页 > 解决方案 > 从 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])

这是正则表达式尝试。

标签: javascriptreactjstypescript

解决方案


您可以拆分路径,删除空段并按位置检索数字:

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]}`);


推荐阅读