我有以下示例网址:#/reports/12/expense/11
。
我需要在报告之后获取ID -> 12.我在这里问的是最合适的方法。我可以在网址中搜索 reports
并在之后获取内容...但是如果在某个时刻我决定更改网址,我将不得不更改我的算法。
您认为这里最好的方法是什么。一些代码示例也非常有帮助。
最佳答案
很难编写面向 future 的代码,因为很难预测我们将来可能会做的疯狂事情!
但是,如果我们假设 id 始终是 URL 中连续数字的字符串,那么您可以简单地查找:
function getReportId(url) {
var match = url.match(/\d+/);
return (match) ? Number(match[0]) : null;
}
getReportId('#/reports/12/expense/11'); // => 12
getReportId('/some/new/url/report/12'); // => 12
关于javascript - 从url获取id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25530837/