Jammming: Doubt on getAccessToken method

Hi there.

Could someone guide me to understand the accessToken and expiresInMatch arrays?
How do I know that it is the second element in those arrays that I need?
In the project Walkthrough Rob uses
accessToken = accessTokenMatch[1];
const expiresIn = Number(expiresInMatch[1]);

How should I know that are the 2nd elements ([1]) that I should use?


Hello, and welcome to the forums!

You could log both accessTokenMatch and expiresInMatch to inspect everything else that is also in the array. In short, it’s because of the regular expression used and the nature of the .match() method.

MDN: String.prototype.match() Documentation

The regular expression being used isn’t using the global flag g, so the first complete match is being returned and there is extra information as well.

Here’s some sample code using the same regular expression and a test URL. The first element is the complete match, and the second element is what’s between the () of the regular expression, which is the part of the URL that you want.

const url = 'https://example.com/callback#access_token=NwAExzBV3O2Tk&token_type=Bearer&expires_in=3600&state=123';

const tokenMatch = url.match(/access_token=([^&]*)/);
const expiresMatch = url.match(/expires_in=([^&]*)/);

/* prints:
  index: 29,
  input: 'https://example.com/callback#access_token=NwAExzBV3O2Tk&token_type=Bearer&expires_in=3600&state=123',
  groups: undefined

/* prints:
  index: 74,
  input: 'https://example.com/callback#access_token=NwAExzBV3O2Tk&token_type=Bearer&expires_in=3600&state=123',
  groups: undefined

Had we used the global flag g with this regular expression, then the results wouldn’t be as helpful because the token would still need to be parsed out.

const tokenMatchGlobal = url.match(/access_token=([^&]*)/g);
// prints: [ 'access_token=NwAExzBV3O2Tk' ]

If you’d like to get more familiar with Regular Expressions, then there’s also a course on it. They’re definitely helpful when parsing and/or processing text.