首页 > 解决方案 > 如何从javascript中的url中提取参数

问题描述

我有这个chrome.identity.getRedirectURL()函数提供的 url

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

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

标签: javascriptvue.jsgoogle-chrome-extensionspotify

解决方案


如果您有类似的网址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&"

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


推荐阅读