【问题标题】:How to get id from url in javascript? [duplicate]如何从javascript中的url获取id? [复制]
【发布时间】:2018-10-28 08:43:04
【问题描述】:

我有一个 url,只想获取 id:

https://web.microsoftstream.com/video/223ac74c-0a2f-4f36-b78b-a8ad8a6e3009

我想我可以在末尾查找“/”并将字符串拆分为子字符串。获取 id 的更优雅/更好的方法是什么:223ac74c-0a2f-4f36-b78b-a8ad8a6e3009?

【问题讨论】:

  • 匹配/\d+$/? split也不错
  • location.pathname.split('/').pop() 是一种方法(假设 url 中没有哈希或查询参数)

标签: javascript regex


【解决方案1】:

您可以使用Array.prototype.substring 或正则表达式

let url = 'https://web.microsoftstream.com/video/112233444';
let id = url.substring(url.lastIndexOf('/') + 1);
console.log(id);

// Or using regex
id = url.match(/\d+$/)[0];
console.log(id);

// If your id is some hash or uuid then
url  = 'https://web.microsoftstream.com/video/223ac74c-0a2f-4f36-b78b-a8ad8a6e3009';
console.log(url.match(/video\/(.*)$/)[1]);

【讨论】:

  • 太棒了,谢谢
  • 我更新了答案,不要忘记在正则表达式末尾添加$ 否则它将匹配url中的任何数字
  • 如果 id 看起来像这样:223ac74c-0a2f-4f36-b78b-a8ad8a6e3009
  • @bierhier 更新了答案。添加了类似的场景
  • 非常感谢,你很好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-05
  • 2012-03-31
  • 2014-03-03
  • 2021-11-05
  • 2023-03-24
  • 2017-10-12
  • 1970-01-01
相关资源
最近更新 更多