I have this url that is provided by the chrome.identity.getRedirectURL()
function
https://jjjnkdmnhdhmfjdlmbljoiclmbojbiec.chromiumapp.org/#access_token=BQDhJnhA4NV2V-2Cn5xYwQyPz4QI5EdY3cu5nNqfgvVt4p4K8fKYtmlfp8ZQYS65ww2rUAZQ7chyZnPDZLlKJEyCfZBRxtr6Q1FpRe9UuiTJ2hT9SMNb-icodIc-I9ADauULDf4JVqvVXoHz1hWvpDWnqln8Yus&token_type=Bearer&expires_in=3600
I need to get the access_token
param value to store the token and use it later with spotify api. What is the best method I can use in javascript?
If you have a url like https://some-url?access_token=1234
you can use 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');
Update Regex
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&"
PLEASE NOTE THAT THE BEGINNING #
AND ENDING &
ARE INCLUDING WITH THIS REGULAR EXPRESSION.