【问题标题】:How to extract param from url in javascript [duplicate]如何从javascript中的url中提取参数[重复]
【发布时间】:2021-01-18 10:03:00
【问题描述】:

我有这个由chrome.identity.getRedirectURL() 函数提供的网址

https://jjjnkdmnhdhmfjdlmbljoiclmbojbiec.chromiumapp.org/#access_token=BQDhJnhA4NV2V-2Cn5xYwQyPz4QI5EdY3cu5nNqfgvVt4p4K8fKYtmlfp8ZQYS65ww2rUAZQ7chyZnPDZLlKJEyCfZBRxtr6Q1FpRe9UuiTJ2hT9SMNb-icodIc-I9ADauULDf4JVqvVXoHz1hWvpDWnqln8Yus&token_type=Bearer&expires_in=3600

我需要获取access_token 参数值来存储令牌并稍后将其与 spotify api 一起使用。我可以在 javascript 中使用的最佳方法是什么?

【问题讨论】:

  • “最佳”取决于多种因素,因此这个问题会吸引固执己见的答案。只需使用任何方法,如字符串拆分或使用 URLSearchParams API。
  • 好的,谢谢。我会选择URLSearchParams API
  • @wOxxOm 错了......这不是查询环
  • 是的,我猜这不是查询字符串
  • @epascarello,URLSearchParams 可以处理任何字符串,包括从 URL 的哈希中提取的子字符串。

标签: javascript vue.js google-chrome-extension spotify


【解决方案1】:

如果您有像https://some-url?access_token=1234 这样的网址,您可以使用URLSearchParams

// window location search returns '?access_token=1234' if the url is 'https://some-url?access_token=1234'
const params = new URLSearchParams(window.location.search);
const token = params.get('access_token');

更新正则表达式

const x = new RegExp(/(#access_token=).*?(&)+/);

const str = 'https://jjjnkdmnhdhmfjdlmbljoiclmbojbiec.chromiumapp.org/#access_token=BQDhJnhA4NV2V-2Cn5xYwQyPz4QI5EdY3cu5nNqfgvVt4p4K8fKYtmlfp8ZQYS65ww2rUAZQ7chyZnPDZLlKJEyCfZBRxtr6Q1FpRe9UuiTJ2hT9SMNb-icodIc-I9ADauULDf4JVqvVXoHz1hWvpDWnqln8Yus&token_type=Bearer&expires_in=3600';

// Use String.prototype.match and pass the Regex 
const result = String(str).match(x);
console.log(result);

// returns
[
  "#access_token=BQDhJnhA4NV2V-2Cn5xYwQyPz4QI5EdY3cu5…9SMNb-icodIc-I9ADauULDf4JVqvVXoHz1hWvpDWnqln8Yus&", 
  "#access_token=", "&", 
  index: 57, 
  input: "https://jjjnkdmnhdhmfjdlmbljoiclmbojbiec.chromiuma…1hWvpDWnqln8Yus&token_type=Bearer&expires_in=3600", 
  groups: undefined
]

// Access the matching substring if there is one using
result[0];
// "#access_token=BQDhJnhA4NV2V-2Cn5xYwQyPz4QI5EdY3cu5nNqfgvVt4p4K8fKYtmlfp8ZQYS65ww2rUAZQ7chyZnPDZLlKJEyCfZBRxtr6Q1FpRe9UuiTJ2hT9SMNb-icodIc-I9ADauULDf4JVqvVXoHz1hWvpDWnqln8Yus&"

请注意,开头 # 和结尾 & 包含在此正则表达式中。

【讨论】:

  • 如果令牌不是查询参数而是path 参数,那么您将使用regular expression
  • 好的,谢谢。我认为 URLSearchParams API 会好的。如果您可以使用正则表达式显示示例,我们将不胜感激。 :)
  • 不确定它是如何被标记为答案的。哈希不会被解析为.a Search Param。
  • var url = 'completeURL'.split('#') var access_token = url[1].slice(12,172) 使用此代码仅获取 access_token
  • 答案已更新:)
猜你喜欢
  • 2010-12-10
  • 1970-01-01
  • 2013-11-21
  • 2014-01-12
  • 2021-10-20
  • 2016-04-24
  • 2021-06-15
  • 2012-03-31
  • 1970-01-01
相关资源
最近更新 更多